C++ Class Constructor and Destructor
C++ Class Constructor and Destructor
A constructor will have exact same name as the class and it does not have any return type at all,
not even void. Constructors can be very useful for setting initial values for certain member
variables.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor can have
parameters. This helps you to assign initial value to an object at the time of its creation as shown in
the following example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use same syntax
and separate the fields by comma as follows:
A destructor will have exact same name as the class prefixed with a tilde and it can neither return
a value nor can it take any parameters. Destructor can be very useful for releasing resources
before coming out of the program like closing files, releasing memories etc.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
When the above code is compiled and executed, it produces the following result: