Q:

C++ program for Constructor and Destructor Declaration, Definition

belongs to collection: C++ programs on various topics

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)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Class Exercise - Read and Print Class, Student... >>
<< C++ program - Polymorphism implementation using Vi...