0

I am trying to overload an operator in the base class but i have to use one of the functions from the derived class, for example i have a Shape abstract class and i derive 3 classes circle, rectangle and square. Now to compare which one has the biggest perimeter i want to overload an operator > to the Shape class and iterate from there in the main, but i don't know how to get the perimeter() from a derived class to the base one.

#include<iostream>
#include<cstring>
using namespace std;
class Shape{
protected:
    char name[5];
public:
    Shape(char *name = " "){
        strcpy(this->name, name);
    }
    virtual double perimeter() = 0;
    bool operator>(const Shape* other){
        ......
    }
};
class Square: public Shape{
private:
    int side;
public:
    Square(char *name = " ", int side = 0): Shape(name){
        this->side = side;
    }
    double perimeter(){
        return 4.0*side;
    }
};
class Rectangle: public Shape{
private:
    int base;
    int height;
public:
    Rectangle(char *name = " ", int base = 0, int height = 0): Shape(name){
        this->base = base;
        this->height = height;
    }
    double perimeter(){
        return 2.0*(base+height);
    }
};
class Circle: public Shape{
private:
    int radius;
public:
    Circle(char *name = " ", int radius = 0): Shape(name){
        this->radius = radius;
    }
    double perimeter(){
        return 2*radius*3.14;
    }
};
Tara
  • 1
  • 1
  • 2
    Just like normal: `bool operator < (const Shape& other) const { return perimeter() < other.perimeter(); }`. Virtual dispatch will take care of calling the right override for the right class. – Yksisarvinen Apr 30 '22 at 14:28
  • What have you tried so far? What went wrong? Your setup looks right, so "just do it". – JaMiT Apr 30 '22 at 14:31
  • Worth reading for operator overloading and why I changed `operator >` to `operator <`, `const Shape*` to `const Shape&` and why is `const` at the end needed: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Yksisarvinen Apr 30 '22 at 14:31
  • Thank you, i just couldn't figure it out. – Tara Apr 30 '22 at 14:55

0 Answers0