FAQ 20.02 What is C s constructor discipline?

FAQ 20.02 What is C++'s constructor discipline?

A constructor is automatically called at the moment an object is created.

Descartes said, "I think, therefore I am." The C++ variation of Descartes' statement is "I am, therefore I can think." In other words, every object that exists ("I am") has been initialized by one of the class's constructors ("I can think"). Except for pathological cases, by the time an object is accessible, it has already been initialized by its constructor.

The developers of a class provide a set of constructors that define how objects of that class can be initialized. When users create objects of that class, they must provide arguments that match the signature of one of the class's constructors. Constructors enhance encapsulation since they force users to create objects in one of the officially supported ways. Users cannot initialize an object's state directly, because this might place the object in an incoherent or illegal state.

In the example from the previous FAQ, the constructor for class Battery is the member function Battery::Battery(int initialCharge). This constructor initializes the protected: data member charge_ to the value passed as the parameter to the constructor. The constructor is called twice in main(), once when yourDiscountBattery is created and once when myNameBrandBattery is created.



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