samedi 30 avril 2022

How to call a derived class function from a base abstract class?

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;
    }
};

Aucun commentaire:

Enregistrer un commentaire