The constructor turns a pile of incoherent, arbitrary bits into a living object. It initializes the object's internal data members, but it may also allocate resources (memory, files, semaphores, sockets, and so on). The word "ctor" is shorthand for the word "constructor." The constructors for class X are member functions named X. Here is an example. class Battery { public: Battery(int initialCharge) throw(); void drain() throw(); protected: int charge_; }; Battery::Battery(int initialCharge) throw() : charge_(initialCharge) { } void Battery::drain() throw() { charge_ -= 5; if (charge_ < 0) charge_ = 0; } int main() { Battery yourDiscountBattery(20); //A Battery object Battery myNameBrandBattery(30); //Another Battery object } There can be more than one constructor for a class. Each constructor has the same name, so the compiler uses their signatures to uniquely identify them. |