Professional Documents
Culture Documents
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();
}