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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.