|
|
|
CONSTRUCTOR & DESTRUCTOR
Those are the special member functions with name of class. These are the methods, which are getting automatically called at the time of object creation. These are basically used to set the initial values of the data member Constructor is a member function, with the same name as its class. It is executed every time an object of the class is created. A constructor has no return type but it can take arguments. It is often used to give initial values to object data members. Constructors can be overloaded, so an object can be initialized in different ways. The constructor method must not return any value so it is written without return type e.g. # include class counter { private : unsigned int cnt; public : counter() { cnt = 0; } void incr() { cnt++; } int givecnt() { return cnt; } } void main() { counter c1; cout<<”\nThe initial count is : “< c1.incr(); c1.incr(); c1.incr(); cout<<”\nThe count after increment is : “<} The constructor functions have some special characteristics as follows: 1. They should be declare in the public section. 2. They are invoked automatically when the objects are created. 3. They do not have return types not even void. 4. They cannot be inherited, though a derived class can call the base class constructor. 5. They can have default arguments. 6. We cannot refer to their address. 7. Constructors cannot be virtual. 8. An object with a constructor cannot be used as a member of a union.
Overloaded Constructor We can define overloaded constructers so that we can set required values at the time of creating the objects. e.g. # include class counter { private : unsigned int cnt; public : counter() { cnt = 0; } counter(int x) { cnt = x; } void incr() { cnt++; } int givecnt() { return cnt; } };
void main() { counter c1,c2(10);; cout<<”\nThe initial count is : “< cout<<”\nThe initial count is : “< c1.incr(); c1.incr(); c2.incr(); c2.incr(); cout<<”\nThe count after increment is : “< cout<<”\nThe count after increment is : “<}
In above example counter c1 is initialized to 0, as constructor without arguments is get called. & c2 get set to 10 as constructor with one argument get called.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|