En este programa vamos a aprender cómo declarar y definir constructor y el destructor en C ++ Programming Language?
Aquí vamos a definir constructor y el destructor utilizando dos tipos diferentes definición de una clase dentro y fuera del segundo definiciones de clases.
# 1 – Las definiciones de constructor y el destructor dentro de la definición de clase
Consideremos el siguiente ejemplo:
#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;
}
salida
Constructor called.
display function called.
Destructorcalled.
# 2 – Definiciones de constructor y destructor definición de clase fuera
#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;
}
salida
Constructor called.
display function called.
Destructorcalled.