Pointers code snippet
Summary
Source code
C++: simple_class_example.cpp
#include <iostream>
#include <string>
using namespace std;
// class Person
// with two private fields name and age
// two public methods to retrieve fields (called "getters")
// and public non-default constructor
class Person {
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
string getName() {
return name;
}
int getAge() {
return age;
}
private:
string name;
int age;
};
int main() {
cout << "Creating a person..." << endl;
Person johnDoe("John Doe", 25);
cout << "Person's name: " << johnDoe.getName() << endl;
cout << "Person's age: " << johnDoe.getAge() << endl;
return 0;
}
Sample run
C/C++
Creating a person...
Person's name: John Doe
Person's age: 25