jeudi 20 octobre 2022

Operator Overloading with polymorphism abstract class c++

I cannot make operator overloading work, and i don't have the clarity why and i want to understand better what is happening.

I got this code:

figure.h

class Figure {
public:
    explicit Figure();
    virtual ~Figure();
    virtual double calculateArea() = 0;

    virtual double getWidth() const;
    virtual void setWidth(double newWidth);

    virtual double getHeight() const;
    virtual void setHeight(double newHeight);

    virtual double getArea() const;
    virtual void setArea(double newArea);

protected:
    double width;
    double height;
    double area;
};

square.h

class Square : public Figure {
public:
    Square( double width, double height );
    virtual ~Square();
    double calculateArea();

    void operator<(Square &f)  {
        cout << "test";
        return this->area > f.area;
    }
};

square.cpp

Square::Square( double _width, double _height ) : Figure() {
    width = _width;
    height = _height;
    area = calcularArea();
}

Square::~Square() {}

double Square::calculateArea() {
    return (width * height);
}

main.cpp

int main() {

    Figure *f1 = new Square(10, 20);
    Figure *f2 = new Square(20, 30);

    if (f1 < f2)  {
        cout << "f1 is bigger than f2";
    } else {
        cout << "f2 is bigger than f1";
    }

    return 0;
}

the result:

  • the cout "test" does not log to the console
  • the operator overloading not working

i tried many things with pointers and function parameters, even moved the operator overload to the Figure class and still not working.

I want to understand WHY and WHAT is happening, and how can i make it work.

Thanks

Aucun commentaire:

Enregistrer un commentaire