Constructor and Destructor in C++
Constructor and Destructor in C++
The constructor is used to allocate the memory if required and constructs the object of the class. Whereas, a destructor is used to perform required clean-up when an object is destroyed . The destructor is called automatically by the compiler when an object gets destroyed. Here, on this page, we will discuss Constructors and Destructors in C++.
Constructor in C++
- When we create an object and don’t assign values the data of that object take up garbage values.
- To make sure that this doesn’t happen we use constructors to assign values to them as soon as they are created or memory is assigned.
The new version of C++ automatically calls a default constructor implicitly to assign a default value in cases when we don’t create a constructor ourselves.
Syntax –
A constructor can be declared –
- Inside the class
- Outside the class (using scope resolution :: operator)
More information
- Constructors have the same name as class name
- They are called using classname and (); example myClass();
- They can also be defined(initialised) outside class by using the class name and scope resolution :: operator.
Example Syntax
class myClass() { // member variables int i; public: // Constructor myClass(){ // initializations here } };
class myClass() { // member variables int i; public: // Constructor declared here myClass(); }; // Constructer defined here myClass::myClass(){ // data member initializations here }
Destructors in C++
We worked with initialising the object values, but what when the scope of the object ends?
We must also destroy the object, right ! For this we use Destructors in C++. We can create our own destructor as follows –
Syntax
- Destructors will never have any arguments.
- The class name is used for the name of the destructor, with a
~
sign as a prefix to it.
class myClass { public: // this automaticlly destroyed // the current instance of the class ~myClass(); };
Let us look at an example how we can implement destructors and constructors together in sync
#include <iostream> using namespace std; class myClass { public: myClass(){ cout << "Constructor called" << endl; } ~myClass(){ cout << "Destructor called" << endl; } }; int main() { myClass obj1; // Constructor Called for obj1 int x = 1; if(x){ myClass obj2; // Constructor Called for obj2 } // Destructor Called for obj2 as obj2 out of scope return 0; }// Destructor called for obj1 as obj1 out of scope
Output –
Constructor called Constructor called Destructor called Destructor called
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment