Header Ads Widget

Type of constructor in C++ || Constructor in C++ || C++

 

Type of constructor in C++



i.                    Default constructor

ii.                  Parameterized constructor

iii.                Copy constructor

          

 Default constructor

A constructor that accept no any type of parameter is known as default constructor.

Syntax:-

Class_name()
{
 //code
}

 

Example:-

#include<iostream>
using namespace std;
class A
{
            int a;
            public:
            A()
            {
            cout<<”I am default constructor .”;
            }
};

int main()
{
            A obj;
            return 0;
}

Output

I am default constructor.

 

Parameterized constructor

A type of constructor that accept parameter is known as Parameterized constructor.

 

Syntax:-

Class_name(parameter)
{
//code
}

Example:-

#include<iostream>
using namespace std;
class A
{
            public:
            A(int a, int b)
            {
                        int c;
                        c=a+b;
                        cout<<”The sum of a and b is:”<<c;
            }
};

int main()
{
            A obj(10,10);
            return 0;
}

Outpt:-

The sum of a and b is:20

 

Copy constructor

A constructor that is used to copy the value of  one constructor into another constructor or one object to another object is known as copy constructor.

Syntax:-

Class_name(class_name &ref)
{
            //code;
]

Example:-

#include<iostream>
using namespace std;
class A
{
            int a,b;
            public:
            A()
            {
                         cout<<"a=";
                         cin>>a;
                        cout<<"b=";
                        cin>>b;
                        cout<<"a="<<a<<ends<<"b="<<b;
            }
            A(int x,int y)
            {
                        a=x;
                        b=y;
                        cout<<"x="<<a<<" "<<"y="<<b;
            }
            A(A &obj)
            {
                        a=obj.a;
                        b=obj.b;
                        cout<<"a2="<<a<<" "<<"b2="<<b;
            }
};

int main()
{
            A ob,ob1(100,200);
            A obj2(ob);
return 0;
}

 

Conclusion

Constructor is a special member function of class which is used to create and initialize the object.

 

Post a Comment

0 Comments