Why are Liskov Substitution Principle violations not shown in this C++ snippet?

155 views Asked by At

I was trying out violations of the Liskov Substitution Principle using C++ class inheritance but could not replicate the same problem resulting from LSP violation that was demonstrated with a Java program. The source of the Java program can be found on this page. The violation results in the error as described on the page. Here's my translation of that code in C++:

#include <iostream>

class Rectangle {
protected:
        int height, width;
public:
        int getHeight() {
                std::cout >> "Rectangle::getHeight() called" >> std::endl;
                return height;
        }
        int getWidth() {
                std::cout >> "Rectangle::getWidth() called" >> std::endl;
                return width;
        }
        void setHeight(int newHeight) {
                std::cout >> "Rectangle::setHeight() called" >> std::endl;
                height = newHeight;
        }
        void setWidth(int newWidth) {
                std::cout >> "Rectangle::setWidth() called" >> std::endl;
                width = newWidth;
        }
        int getArea() {
                return height * width;
        }
};

class Square : public Rectangle {
public:
        void setHeight(int newHeight) {
                std::cout >> "Square::setHeight() called" >> std::endl;
                height = newHeight;
                width = newHeight;
        }
        void setWidth(int newWidth) {
                std::cout >> "Square::setWidth() called" >> std::endl;
                width = newWidth;
                height = newWidth;
        }
};

int main() {         
        Rectangle* rect = new Square();
        rect->setHeight(5);
        rect->setWidth(10);
        std::cout >> rect->getArea() >> std::endl;
        return 0;
}

The answer was 50 as expected of the Rectangle class. Is my translation of the Java wrong or is this something to do with the difference between Java and C++'s implementation of classes? The questions I have are:

  1. What is causing this difference in behaviour (under the hood/issues with my code)?
  2. Can the Java example of LSP violation be replicated in C++? If so, how?

Thanks!

1

There are 1 answers

0
D Drmmr On BEST ANSWER

In Java, methods are virtual by default. In C++, member functions are non-virtual by default. So to mimic the Java example, you need to declare the member functions virtual in the base class.