Q:

C++ program for Constructor and Destructor Declaration, Definition

0

C++ program for Constructor and Destructor Declaration, Definition

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#1 – Definitions of Constructor and Destructor inside class definition

Let’s consider the following example:

#include <iostream>

using namespace std;

class Example{
	public:
		//default constructor
		Example(){cout<<"Constructor called."<<endl;}
		//function to print message
		void display(){
			cout<<"display function called."<<endl;
		}
		//Destructor 
		~Example(){cout<<"Destructor  called."<<endl;}
};

int main(){
	//object creation
	Example objE;
	
	objE.display();
	
	return 0;
}

Output

    Constructor called.
    display function called.
    Destructorcalled.

#2 – Definitions of Constructor and Destructor outside class definition

#include <iostream>

using namespace std;

class Example{
	public:
		//default constructor
		Example();
		//function to print message
		void display();
		//Destructor 
		~Example();
};

//function definitions
Example::Example(){
	cout<<"Constructor called."<<endl;	
}

void Example::display(){
	cout<<"display function called."<<endl;	
}

Example::~Example(){
	cout<<"Destructor  called."<<endl;	
}

int main(){
	//object creation
	Example objE;
	
	objE.display();
	
	return 0;
}

Output

    Constructor called.
    display function called.
    Destructorcalled.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now