Constructor in c++

(q) Why constructor in c++? 

Answer: 
One of the goals of c++ is to create such type of class which is very similar to basic data type like int, char, float etc. It is possible in basic data type like int, char etc we can initialize the data type at the time of creation. 

Example: 
#include <iostream.h>
#include <stdio.h>
int main()
{
    int a=6;  //initialization at the time
    char b='v'// of creation
    clrscr();
    cout<<a;
    cout<<b;
    getch();
    return 0;
}
Output: 
6 
v 

but a member function or friend function cannot initialize the data member at the time of creation of respective objects. 
Example: 

/* Disadvantage of member functions */
#include<iostream.h>
#include<stdio.h>
class country
{
    char *name;
    long int population;
    public:
    void getdata()
    {
         Name=”USA”;
         Population=700000000;
    }
    void display()
     {
         cout<<Name;
         cout<<Population;
    }
};
int main()
{
    country usa,india; //creating objects
    clrscr();
    usa.display(); //object has not been initialized by member      //function
    india.display(); // getdata automatically
    getch();
    return 0;
}
Output: garbage value 

Hence C++ introduce a special type of function which is called constructor and it  can initialize the data member of respective objects at the time of creation like basic data type int, float etc. 
Example: 
/* advantage of constructor */
#include<iostream.h>
#include <stdio.h>
class country
{
    char *name;
    long int population;
    public:
    country()
    {
         name="India";
         population=1000000000;
    }
    void display()
    {
         cout<<name;
         cout<<population;
    }
};
int main()
{
    country usa,india; //creating objects
    clrscr();
    india.display(); //object has been initialize at the time of creation
    getch();
    return 0;
}
Output: 
india 
1000000000 

No comments: