Constructor & Destructor
Posted on November 18, 2022 • 1 minutes • 200 words
1. Constructor
- A special type of member function.
- Constructor called automatically when an object is created.
- Constructor Name is same as Class Name.
- Constructor has no return type.
Related videos
Constructor Types
- Default Constructor.
- Parameterized Constructor.
2. Destructor
- A special type of member function.
- Destructor called automatically when an object is deleted.
- Destructor Name is same as Class Name.
- Destructor has no return type.
Example Program
class Rectangle
{
public:
// Default Constructor
Rectangle()
{
std::cout << "Default Constructor called" << std::endl;
length = 0;
width = 0;
}
// Parameterized Constructor
Rectangle(int len, int wid)
{
std::cout << "Parameterized Constructor called" << std::endl;
length = len;
width = wid;
}
// Destructor
~Rectangle()
{
std::cout << "Destructor called " << std::endl;
}
// functions
double getArea()
{
return length * width;
}
// data members
double length;
double width;
};
int main()
{
// Program start here
Rectangle r1(20,20);
// accessing the members
// dot operator "."
// obectName.memberName
// objectName.functionName()
// r1.length = 10;
// r1.width = 10;
double area1 = r1.getArea();
std::cout << "Area1 :" << area1 << std::endl;
Rectangle r2;
double area2 = r2.getArea();
std::cout << "Area2 :" << area2 << std::endl;
return 0;
}