YouTip LogoYouTip

Cpp Constructor Destructor

## Class Constructor A class **constructor** is a special member function of a class that is automatically executed whenever a new object of that class is created. The constructor has the same name as the class and has no return type (not even `void`). Constructors are typically used to set initial values for member variables. If a constructor is not explicitly defined, the compiler automatically generates a default constructor that does nothing. The following example helps to better understand the concept of a constructor: ## Example #includeusing namespace std; class Line{public: Line(); // Constructor declaration void setLength(double len); double getLength()const; private: double length; }; // Constructor definition Line::Line(){cout<<"Object is being created"<<endl; length = 0.0; // Explicitly initialize member variable}void Line::setLength(double len){length = len; }double Line::getLength()const{return length; }// Main function of the program int main(){Line line; // Set length line.setLength(6.0); cout<<"Length of line : "<<line.getLength()<<endl; return 0; } When the above code is compiled and executed, it produces the following result: Object is being created Length of line : 6 ## Parameterized Constructor The default constructor takes no parameters, but if needed, a constructor can also have parameters. This allows an object to be initialized with a value at the time of creation, eliminating the need to call a `set` function separately, as shown in the following example: ## Example #includeusing namespace std; class Line{public: Line(double len); //
← Net WebpageNet Url Header β†’