this
Inside a method, this is a pointer to the object the method was called on. It's useful when a parameter has the same name as a member:
#include <iostream>
#include <string>
using namespace std;
class Cat {
private:
string name;
public:
void setName(string name) {
this->name = name; // this->name is the member, name is the parameter
}
string getName() const { return name; }
};
int main() {
Cat c;
c.setName("Tom");
cout << c.getName() << "\n";
return 0;
}Output
Tom
Tip:
this->nameis short for(*this).name. The arrow->reaches a member through a pointer.
static: one value shared by all objects
A normal member belongs to each object. A static member belongs to the class itself, so all objects share one copy. Here it counts how many objects were created:
#include <iostream>
using namespace std;
class Robot {
public:
static int count;
int id;
Robot() {
count++;
id = count;
}
};
int Robot::count = 0; // the shared value is created once, outside the class
int main() {
Robot a, b, c;
cout << "Robots built: " << Robot::count << "\n";
cout << "c has id " << c.id << "\n";
return 0;
}Output
Robots built: 3 c has id 3
Defining methods outside the class
In bigger programs the class only lists its methods, and their bodies are written below using ClassName::. This keeps the class short and easy to scan:
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
Circle(double r);
double area() const;
};
Circle::Circle(double r) : radius(r) {}
double Circle::area() const {
return 3.14159 * radius * radius;
}
int main() {
Circle c(2);
cout << c.area() << "\n";
return 0;
}Output
12.5664
Remember: In real projects the class goes in a header file (
Circle.h) and the method bodies inCircle.cpp. You'll see how in the last module.