You are on page 1of 13

Constructor

Types of constructor
Constructor overloading
Destructor:

Constructor:
 Constructor is a special type of member-function
that have the same name as of class name.
 Constructor get call automatically with the
creation of object.
 Constructor do not have return type.
 Constructor can get arguments.
 Constructor scope must be public it can not be
private.
 Constructor may be overloaded
 The main purpose of constructor is to initialize the
variables.
 To allocate memory , to reserve memory .
e.g.
class student
{
Public:
Student()  constructor
{
………..
}
};
COMPLETE EXAMPLE:
#include<iostream.h>
#include<conio.h>
class student
{
public:
student()
{
cout<<"this is a constructor ";
}
};
void main()
{
//student stu;
clrscr();
student obj1;
getch();
}

#include<iostream.h>
#include<conio.h>
class student
{
private:
int a , b;
public:
student()
{
a = 10;
b = 20;
cout<<a <<endl <<b;
}
};
void main()
{
clrscr();
student obj1;
getch();
}
#include<iostream.h>
#include<conio.h>
class student
{
private:
int a , b;
public:
student(): a(10) , b(20) { }
void show()
{
cout<<a <<endl<<b;
}

};
void main()
{
clrscr();
student obj1;
obj1.show();
getch();
}
#include<iostream.h>
#include<conio.h>
class student
{
private:
int a , b;
public:
student()
{
a = 10;
b = 20;
cout<<a <<endl <<b;
}
void getdata()
{
cout<<endl<<"enter values of a and b ";
cin>>a >> b;
}
void showdata()
{
cout <<a <<endl <<b;
}
};
void main()
{
clrscr();
student obj1;
obj1.getdata();
obj1.showdata();
getch();
}

#include<iostream.h>
#include<conio.h>
class student
{
private:
int a , b;
public:
student(int x , int y): a(x) , b(y) { }
void show()
{
cout<<a <<endl<<b;
}

};
void main()
{
clrscr();
student obj1(23,56);
obj1.show();
getch();
}

Constructor overloading example:


#include<iostream.h>
#include<conio.h>
class test
{
private:
int no;
char *name;
float per;
public:
test()
{
no=0;
name ="ABC";
per = 0;
}
test(int n)
{
no=n;
name ="ABC";
per = 0;
}
test(int n , char na[])
{
no=n;
name =na;
per = 0;
}
test(int n , char na[], float p)
{
no=n;
name =na;
per = p;
}
void show()
{
cout<<endl<<no<<endl<<name<<endl<<per;
}
};
void main()
{
int n ;
char *na;
float p;
clrscr();
n=100;
na="ABCD";
p=67.8;
test t(n,na,p);
test t1(n,na);
t.show();
//t1.show();
getch();
}

Passing object as arguments:


Operator Overloading:

You might also like