Types of constructors


Type of Constructors.

⇒In C++  a constructor is an special Member function which automatically gets called . Whenever, the object of a class is initialised.
⇒The constructor is defined by defining the Member function or method name and class name are same or similar.
↦There are four types of constructors . They are
A】Default Constructor
⇒Constructor are accessed automatically, when the object is initialised or created.
⇒ one's object is created constructors are invoked automatically.
Syntax:-
Class_name <object_name>;
Ex:-A.obj;
  • Sample program
#include<iostream.h>
class x
{
public:
x()
{
cout<<"Hi shashi";
}};
int main()
{
x a;
return 0;
}
B】Parameterized Constructor

⇒In C++, Parametrized Constructor is as like as default constructor .But, the constructor which has the arruguments is known as the Parameterized Constructor.
  • Sample program
#include<iostream.h>
class area
{
public:
area(double r)
{
cout<<"area of circle="<<(r*r*3.14)<<endl;
}};
int main()
{
area a(3.5);
return 0;
}
C】Copy Constructor
⇒A copy constructor is a Member function which initializes an object using another object of the same class.


  • Sample program

#include<iostream.h>
class emp
{
int id;
public:
emp();
emp(int s)
{
id=s;
}
emp(emp &a)
{
id=a.id;
}
void show()
{cout<<id; }
};
int main()
{
  emp x(50);
  emp y(x);
  emp z=x;
  emp t=x;
  cout<<"id of x=";
   x.show();
  cout<<"\nid of y=";
    y.show();
  cout<<"\nid of z=";
    z.show();
  cout<<"\nid of t=";
    t.show();
return 0;
}

Comments

Popular posts from this blog

History of C language

Lab programs of C

Algorithm Pseudopods Flow-chat