C++ Constructor

Constructor


  • Constructor is a special member function of a class having same name as that of class.
  • Constructor is automatically called when we declare object of class.
  • Defining a Constructor is good practice because in the absence of a user define constructor, data members of class may get garbage.

There are two methods to define constructor:
  1. Inside the Class
  2. Outside the Class

Constructor Inside the Class


Syntax


class class_name
{
    private/public/protected:
    class_name()
    {
         Statement;
    }
}


Program to show constructor inside class



#include<iostream.h>
#include<conio.h>
class data
{
    int a;
    float b;
    public:
    data()
    {
       a=10;
       b=12.4;
    }
    void show()
    {
        cout<<"\n a="<<a;
        cout<<"\n b="<<b;
    }
};
void main()
{
    clrscr();
    data d;
    d.show();
    getch();
}


Output


a=10
b=12.4


Constructor Outside the Class


Syntax


class class_name
{
    private/public/protected:
    class_name();
}
class_name::class_name()
{
    Statement;
}


Program to show constructor outside class



#include<iostream.h>
#include<conio.h>
class data
{
    int a;
    float b;
    public:
    data();
    void show()
    {
        cout<<"\n a="<<a;
        cout<<"\n b="<<b;
    }
};
data::data()
{
    a=10;
    b=12.4;
 }
void main()
{
    clrscr();
    data d;
    d.show();
    getch();
}


Output


a=10
b=12.4

Back To Top