Constructor and Destructor functions are Member Functions of a class having some special property.
Constructor function gets invoked when an object of a class is constructed (declared) and destructor function gets invoked when the object is destructed (goes out of scope).
Use of Constructor and Destructor function of a class
-
Constructor function is used to initialize member variables to pre-defined values as soon as an object of a class is declared.
-
Constructor function having parameters is used to initialize the data members to the values passed values, upon declaration.
-
Generally, the destructor function is needed only when constructor has allocated dynamic memory.
Defining Constructor and Destructor functions
The example below illustrates how constructor and destructor functions are defined:
class myclass { private: int number; public: myclass()//constructor { number=10; } ~myclass()//destructor { //nothing needed } };
A few points to note:
-
Both of the functions have the same name as that of the class, destructor function having (~) before its name.
-
Both constructor and destructor functions should not be preceded by any data type (not even void).
-
These functions do not (and cannot) return any values.
-
We can have only the constructor function in a class without destructor function or vice-versa.
-
Constructor function can take arguments but destructors cannot.
-
Constructor function can be overloaded as usual functions.
Example 1: Using constructor function to initialize data members to pre-defined values
//Example Program in C++ #include<iostream.h> class myclass { private: int a; int b; public: myclass() { //here constructor function is used to //initialize data members to pre-def //values a=10; b=10; } int add(void) { return a+b; } }; void main(void) { myclass a; cout<<a.add(); }
Example 2: Using constructor function to initialize data members to values passed as arguments
//Example Program in C++
#include<iostream.h>
class myclass
{
private:
int a;
int b;
public:
myclass(int i, int j)
{
a=i;
b=j;
}
int add(void)
{
return a+b;
}
};
void main(void)
{
//notice how the object of the class
//has been declared
//it can be thought as
// myclass a;
// a=myclass(10,20)
myclass a(10,20);
cout<<a.add();
}
Notice that there is no destructor function in both the examples, just because we don’t need them.
I will discuss destructor functions in detail in the coming articles.
So, keep checking!
Related Articles: