Home » Code Snippets » C/C++ Code Snippets

C++ program for Constructor and Destructor Declaration, Definition

In this program we will learn how to declare and define constructor and destructor in C++ programming language?

Here we will define constructor and destructor using two different types one inside class definition and second outside of class definitions.

#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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.