Methods and Constructors
GOALWrite functions inside a class, and make an object valid the moment it is created.
A function written inside a class is a method — it reaches its own object's data directly. A constructor is a special method that runs automatically when the object is created. Its value: "I forgot to fill that in" stops being possible.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <string>
using namespace std;
class Rect {
private:
int w, h;
public:
Rect(int width, int height) {
w = width;
h = height;
}
int area() {
return w * h;
}
int perimeter() {
return 2 * (w + h);
}
};
int main() {
Rect r(3, 4);
cout << r.area() << endl;
cout << r.perimeter() << endl;
Rect small(2, 2);
cout << small.area() << endl;
return 0;
}12 14 4
//LINE BY LINE
Watch it run
Rect r(3, 4); — the constructor fills w and h in one go.
What a constructor protects you from
Without a constructor an object can exist half-filled — some fields set, others holding rubbish. A constructor makes that state impossible.
Rect a; // w and h hold junk — the compiler allows it
a.w = 3; // now half-built
// ... a.h is still junk when area() is called
Rect b(3, 4); // with a constructor this is the ONLY way inOnce you define a constructor with arguments, Rect a; no longer compiles. That is not a bug — it is the entire point.
What self and this actually are
Inside a method, writing w works because the compiler knows WHICH object's w you mean — the method silently receives the object it was called on. That object is this.
int area() {
return w * h; // really this->w * this->h
}