November 18, 2022

Constructor & Destructor

Posted on November 18, 2022  •  1 minutes  • 200 words

1. Constructor

  1. A special type of member function.
  2. Constructor called automatically when an object is created.
  3. Constructor Name is same as Class Name.
  4. Constructor has no return type.

link

Constructor Types

  1. Default Constructor.
  2. Parameterized Constructor.

2. Destructor

  1. A special type of member function.
  2. Destructor called automatically when an object is deleted.
  3. Destructor Name is same as Class Name.
  4. 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;
}
Follow me

I work on everything coding and share developer memes