program to illustrate the communication of object: Note Even an array of objects can be created for a class. It is declared and defined in the same way as any other type of array. Example : student s[ ]; Where student is the class name and s[ ] is objects created for the student class. .
Introduction to Constructors The definition of a class only creates a new user defined data type. The instances of the class type should be instantiated (created and initialized) . Instantiating object is done using constructor. Chapter Page - - .
. Need for Constructors An array or a structure in c++ can be initialized during the time of their declaration. For example struct sum int n1,n2; }; class add int num1,num2; }; int main() int arr[]={ , , }; //declaration and initialization of array sum s1={ , }; //declaration and initialization of structure object add a1={ , }; // class object declaration and initialization throws compilation error Member function of a class can access all the members irrespective of their associated access specifier. The initialization of class type object at the time of declaration similar to a structure or an array is not possible because the class members have their associated access specifiers (private or protected or public).
Therefore Classes include special member functions called as constructors . The constructor function initializes the class object. . Declaration and Definition When an instance of a class comes into scope, a special function called the constructor gets executed.
The constructor function name has the same name as the class name. The constructors return nothing. They are not associated with any data type. It can be defined either inside class definition or outside the class definition.
Example : #include<iostream> using namespace std; class Sample int i,j; public : int k; Sample() i=j=k= ; //constructor defined inside the class }; Illustration . A constructor defined inside the class specification. Chapter Page - - . .
Functions of constructor As we know now that the constructor is a special initialization member function of a class that is called automatically whenever an instance