FAQ 20.01 What is the purpose of a constructor?

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net