0

I am new to object oriented programming in C++ and i've been wondering if there is a way of calling function of child class from parent class

#include <iostream>
using namespace std;
class Shape
{
public:
    void display()
    {
        cout<< "This is a shape\n";
    }
};
class Polygon: public Shape
{
public:
    void display()
    {
        Shape::display();

        cout<< "Polygon is a shape\n";
    }
};
class Rectangle : public Polygon
{
public:
    void display()
    {
        Polygon::display();
        cout<< "Rectangle is a polygon\n";
    }
};
class Triangle: public Polygon
{
public:
    virtual void display()
    {
        cout<<"Triangle is a polygon\n";
    }
};
class Square: public Rectangle
{
public:
    void display()
    {
        Rectangle::display();
        cout<<"Square is a rectangle\n";
    }
};
int main() {
    Square shape;
    shape.display();

    return 0;
}

I want to call the display function in Triangle class from the Polygon class. Or is there any other way to call the display of every class by using a single object and not changing the given inheritance level?

  • 5
    It seems you missed a couple of things for polymorphism to work. Please invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn more. – Some programmer dude Jul 13 '21 at 11:01
  • 1
    You may use virtual functions, but that depends on what you need to achieve right now and what functionality you expect to implement in your classes in future. – CiaPan Jul 13 '21 at 11:02
  • [Is deriving square from rectangle a violation of Liskov's Substitution Principle?](https://stackoverflow.com/questions/1030521/is-deriving-square-from-rectangle-a-violation-of-liskovs-substitution-principle) – Evg Jul 13 '21 at 11:02
  • If you want `virtual` dispatch, make the base class member function `virtual` and `override` in the derived classes. [example](https://godbolt.org/z/1zo4KP5na) – Ted Lyngmo Jul 13 '21 at 11:08

0 Answers0