Cpp magic methods
From wikinotes
C++ defines magic methods that are called when objects are added together, subtracted, multiplied etc.
constructor/destructor
In cpp, constructurs are a functions defined without type, and with the same name as the class.
They can still have specifiers applied to them, however (explicit, ...).
// header class MyClass } int *ptr; public: MyClass (int, int); // constructor ~MyClass; // destructor }; // source MyClass::MyClass (int a, int b) { cout << "constructed with args" << a << b << endl; } MyClass::~MyClass (){ cout << "class being destroyed" << endl; delete ptr; }The destructor is run when:
- an object instantiated on the stack goes out of scope
- an object instantiated in memory is deleted with
delete <object>
.
Overloading Arithmetic
Classes can also be overloaded so that arithmetic can be performed on them.
NOTE:
this isn't clear at all...
class MyDate { int seconds_since_unixtime; } // returntype class::operator argument (in this case, a reference) MyDate MyDate::operator+ ( MyDate& var )