COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS

CONSTRUCTORS AND DESTRUCTORS(PROGRAMS)

  1. Program to find area of a circle using class, constructor functions and destructor.

#include<iostream.h>
#include<conio.h>
class Circle
{
float r,a; //r and a are private
public:
Circle()
//Non parameterized or Default Constructor
{
r=0.0;
a=0.0;
}
Circle(float rad)
//Parameterized Constructor
{
r = rad;
a = 3.1415*r*r;
}
Circle(Circle &obj) //Copy Constructor
{
r = obj.r;
a = obj.a;
}
~Circle()
{
cout<<"\nThe object is being destroyed....";
}
void take()
{
cout<<"Enter the value of Radius: ";
cin>>r;
}
void calculate()
{
a = 3.1415*r*r;
}
void display()
{
cout<<"\nThe Radius of the Circle = "<<r;
cout<<"\nThe Area of the Circle = "<<a;
}
};
void main()
{ clrscr();
Circle c1; /*Default Constructor will be called implicitly. ie c1.r = 0.0 and c1.a = 0.0 */
Circle c2(10.3);
//Parameterized Constructor will be called implicitly
Circle c3(c2);
//Copy Constructor will be called implicitly
c1.take();
c1.calculate();
c1.display();
c2.display();
c3.display();
getch();
}

  1. Program to process student data using class concept, constructors and destructor.

#include<iostream.h>
#include<conio.h>
class Student
{
float m1,m2,m3,total,avg;
public:
Student()
{
m1=0.0;
m2=0.0;
m2=0.0;
total=0.0;
avg=0.0;
}
Student(float x,float y,float z)
{
m1=x;
m2=y;
m3=z;
total=m1+m2+m3;
avg=total/3;
}
Student(Student &Test)
{
m1=Test.m1;
m2=Test.m2;
m3=Test.m3;
total=Test.total;
avg=Test.avg;
}

~Student()
{
cout<<"The Object is being Destroyed....";
}
void readProcess()
{
cout<<"\nEnter the 3 Subject marks of a student: ";
cin>>m1>>m2>>m3;
total=m1+m2+m3;
avg=total/3;
}
void display()
{
cout<<"\nTotal Marks = "<<total;
cout<<"\nAverage Marks = "<<avg;
}
};
void main()
{
clrscr();
Student S1;
Student S2(50.5,90.0,75.5);
Student S3=S2;
S1.readProcess();
S1.display();
S2.readProcess();
S2.display();
S3.display(); getch();
}

 

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( mrkdata@yahoo.com )


Warning: include_once(../../ebooks-footer19.php): Failed to open stream: No such file or directory in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors16.php on line 202

Warning: include_once(): Failed opening '../../ebooks-footer19.php' for inclusion (include_path='.:/opt/cpanel/ea-php83/root/usr/share/pear') in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors16.php on line 202

Warning: include_once(../../../footer19.php): Failed to open stream: No such file or directory in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors16.php on line 204

Warning: include_once(): Failed opening '../../../footer19.php' for inclusion (include_path='.:/opt/cpanel/ea-php83/root/usr/share/pear') in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors16.php on line 204