Problem Statement - 02A-2016
Differentiate between Constructor and Destructor functions giving suitable example using a class in C++. When does each of them execute?
Solution
PART 1:
Constructor |
Destructor |
A constructor function has same name as the class |
A destructor function has same name as the class preceded by ~ symbol |
Example:
class Exam
{
int Eno; float Marks;
public:
Exam() //Constructor
{
Eno=1; Marks = 100;
cout<<”Constructor executed...”<<endl;
}
void Show()
{
cout<<Eno<<”#”<<Marks<<endl;
}
~Exam() //Destructor
{
cout<<”Exam Over”<<endl;
}
};
void main()
{
Exam E; //Executes constructor
E.Show();
PART 2:
Execution of Constructor and Destructor:
Constructor |
Destructor |
A constructor executes by itself at the time of object creation |
A destructor executes by itself when the scope of an object ends |
CSKC| Created: 10-Jan-2019 | Updated: 16-Jan-2019|CBSE12D-2016
Post Views:
597