Constructors and Destructors
Constructors and Destructors
and
Destructors
Constructors
• A constructor is a special member function whose
task is to initialize the objects of its class.
• It is special because its name is same as the class
name.
• The constructor is invoked whenever an object of its
associated class is created.
• It is called constructor because it constructs the
values of data members of the class.
Constructor - example
class add • When a class contains a
{ constructor, it is guaranteed
int m, n ; that an object created by the
public : class will be initialized
add (void) ; automatically.
------
}; • add a ;
add :: add (void) • Not only creates the object a
{ of type add but also initializes
m = 0; n = 0; its data members m and n to
zero.
}
Constructors
continue …
• Add( ) ; // No arguments
The statement
I 2 = I 1;
will not invoke the copy constructor.