Changing signature while Overriding in C++

1.6k views Asked by At

I have a base class

class Shape{
    public:
        virtual int getArea()=0;
}

I want to change the signature while overriding like this:

class Rectangle : class Shape{
    public:
        int getArea(int someParameter = 0){
            return 0;
        }
}

Is it possible somehow to achieve this, as I am using default value for newly added parameter?

2

There are 2 answers

0
Some programmer dude On BEST ANSWER

The only solution I can see is that you implement both int getArea() and int getArea(int), where one function can call the other (for example int getArea() { return getArea(0); }). You can not have the overload taking an argument have a default argument then.

0
Andrey  Yankovich On

You need to overload your virtual function. But if you overloaded virtual function, you will get a warning "hides overloaded virtual function"

Solution is override function with native signature and overload it with virtual prefix.

Example:

class A {
   virtual void foo(int) {...}
};

class B: public A {
   void foo(int i) override {
       A::foo(i);
   }
   
   virtual void foo(const std::string& str) {
       ...
   }
};