-2

If I want to initialize a class Square

class Square : public Rectangle {
    public Square(int length)
    {
        this->length = length;
        this->width = length;
    }
}

derived from a class Rectangle

class Rectangle {
    protected int length, width;

    public Rectangle(int length, int width)
    {
        this->length = length;
        this->width = width;
    }

    public int getArea() { return length * width; }
}

I'll do it like

Square * s = new Square(5);
cout << s->getArea() << endl;

What are the benefits of doing it like

Rectangle * r = new Square(5);
cout << r->getArea() << endl;

instead and initializing the object as a base class object?

po0l
  • 98
  • 8

1 Answers1

3

You have an interface and an implementation of that interface. This is part of how inheritance and polymorphism work together.

Rectangle *r = new Square works only if Square derives from Rectangle. Any object that is a Rectangle descendant can be assigned to a Rectangle* pointer.

Say all your code needs is a Rectangle* pointer to do its work. The code doesn't need to care whether it operates on a Square object in memory. Perhaps you have to make that decision based on user input at run-time, or certain business rules, etc. Polymorphism allows that. The interface ensures that the needed Rectangle functionality is available, and how to use it. The compiler takes care of delegating to the implementation accordingly.

po0l
  • 98
  • 8
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770