Constructor & Destructor.
Constructor & Destructor.
Programming
Content
• Constructors
• Destructors
Constructors
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Constructors (Parameters)
#include <iostream>
using namespace std;
int main() {
class Student { // The class
// Create Student objects and call the constructor with
public: // Access specifier
different values
string name; // Attribute
Student obj1("Padma", 45729, "A+");
int id; // Attribute
Student obj2("Shetu", 45728, "B+");
string bg; // Attribute
// Print values
Student(string x, int y, string z) {
cout << obj1.name << " " << obj1.id << " " << obj1.bg << "\n";
// Constructor with parameters
cout << obj2.name << " " << obj2.id << " " << obj2.bg << "\n";
name = x;
return 0;
id = y;
}
bg = z;
}
};
Constructors (Parameters)...
Student::Student(string x, int y, string z) // Constructor
#include <iostream>
definition outside the class
using namespace std;
{
name = x;
class Student {
id = y;
public:
bg = z;
string name;
}
int id;
int main() {
string bg;
Student obj1("Padma", 45729, "A+");
Student obj2("Shetu", 45728, "B+");
Student(string x, int y, string z);
cout << obj1.name << " " << obj1.id << " " << obj1.bg << "\n";
// Constructor declaration
cout << obj2.name << " " << obj2.id << " " << obj2.bg << "\n";
return 0;
};
}
Destructors
• Destructors are functions which are just the opposite of constructors.
We all know that constructors are functions which initialize an object.
On the other hand, destructors are functions which destroy the object
whenever the object goes out of scope.
• Destructor has the same name as that of the class with a tilde (~) sign
before it.
• A destructor is always non-parameterized, it gets called when the
object goes out of scope and destroys the object.
Destructors...
#include <iostream>
using namespace std;
class Student
{
public: int main()
Student() {
{ Student s1; //creating an object
cout<<"Constructor Called"<<endl; Student s2; //creating an object
} return 0;
~Student() }
{
cout<<"Destructor Called"<<endl;
}
};
Example
#include <iostream>
void show()
using namespace std;
{
class Student
cout<<"Function Called"<<endl;
{
}
public:
};
Student()
int main()
{
{
cout<<"Constructor Called"<<endl;
Student s1;
}
Student s2;
~Student()
s1.show();
{
cout<<"Destructor Called"<<endl;
return 0;
}
}