Chapter08 C++
Chapter08 C++
8.1 Introduction
8.2 Constructors
// Program - 8.1
// to determine constructors and destructors
#include<iostream.h>
#include<conio.h>
class simple
{
private:
int a,b;
public:
simple()
{
a= 0 ;
b= 0;
cout<< “\n Constructor of class-simple “;
}
~simple()
{
cout<<“\n Destructor of class – simple .. “;
}
void getdata()
{
cout<<“\n Enter values for a and b... “;
cin>>a>>b;
}
void putdata()
{
cout<<“\nThe two integers .. “<<a<<‘\t’<< b;
cout<<“\n The sum of the variables .. “<< a+b;
}
};
void main()
{
simple s;
s.getdata();
s.putdata();
}
185
When the above program is executed, constructor simple() is
automatically executed when the object is created. Destructor ~
simple() is executed, when the scope of the object ‘s’ is lost, i.e., at the
time of program termination.
186
// Program - 8.2
// To demonstrate constructor overloading
# include<iostream.h>
#include<conio.h>
class add
{
int num1, num2, sum;
public:
add()
{
cout<<“\n Constructor without parameters.. “;
num1= 0;
num2= 0;
sum = 0;
}
add ( int s1, int s2 )
{
cout<<“\n Parameterized constructor... “;
num1= s1;
num2=s2;
sum=NULL;
}
add (add &a)
{
cout<<“\n Copy Constructor ... “;
num1= a.num1;
num2=a.num2;
sum = NULL;
}
void getdata()
{
cout<<“Enter data ... “;
cin>>num1>>num2;
}
void addition()
{
sum=num1+num2;
}
void putdata()
{
cout<<“\n The numbers are..”;
cout<<num1<<‘\t’<<num2;
cout<<“\n The sum of the numbers are.. “<< sum;
}
};
void main()
{
add a, b (10, 20) , c(b);
a.getdata();
a.addition();
b.addition();
c.addition();
cout<<“\n Object a : “;
a.putdata();
cout<<“\n Object b : “;
b.putdata();
cout<<“\n Object c.. “;
c.putdata();
}
187
OUTPUT:
Parameterized Constructor...
Copy Constructors…
Enter data .. 5 6
Object a:
Object b:
Object c:
188
Note: char, float double parameters can be matched with int data
type due to implicit type conversions
189
// Program – 8.3
// To demonstrate constructor overloading
# include<iostream.h>
#include<conio.h>
class add
{
int num1, num2, sum;
public:
add()
{
cout<<“\n Constructor without parameters.. “;
num1= ‘\0’;
num2= ‘\0’;
sum = ‘\0’;
}
void getdata()
{
cout<<“Enter data ... “;
cin>>num1>>num2;
}
void addition(add b)
{
sum=num1+ num2 +b.num1 + b.num2;
}
add addition()
{
add a(5,6);
sum = num1 + num2 +a.num1 +a.num2;
}
void putdata()
{
cout<<“\n The numbers are..”;
cout<<num1<<‘\t’<<num2;
cout<<“\n The sum of the numbers are.. “<< sum;
}
};
190
void main()
{
clrscr();
add a, b (10, 20) , c(b);
a.getdata();
a.addition(b);
b = c.addition();
c.addition();
cout<<“\n Object a : “;
a.putdata();
cout<<“\n Object b : “;
b.putdata();
cout<<“\n Object c.. “;
c.putdata();
}
8.6 Destructors
192
Example :
class simple
{
——
——
public :
~simple()
{
.......................
}
}
193
Exercises
Constructor Destructor
1. Should be declared under - scope - scope
2. overloading is - -
3. Is executed when an
object is
The function of a
194