2

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?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Kumar
  • 1,536
  • 2
  • 23
  • 33
  • 2
    If you change signature you are no longer overriding, you are overloading. And no, it's no longer possible to use polymorphism as `Shape::getArea` and `Rectangle::getArea` are two different functions. – Some programmer dude Jun 11 '15 at 06:26
  • @JoachimPileborg: I understand that, but is there any way out? – Kumar Jun 11 '15 at 06:27
  • @Abhinav : This is not possible. you can get some come information here http://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class – Spanky Jun 11 '15 at 06:29
  • You could probably get away by defining a separate hierarchy of "AreaParameter", declaring the virtual taking a pointer or a reference to such parameter (`virtual int getArea(const AreaParameter &p = AreaParameter())`), doing a real override in the subclass and in there downcast the parameter type. (Or in general by employing any double dispatch technique...) – peppe Jun 11 '15 at 06:31

2 Answers2

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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) {
       ...
   }
};

Andrey Yankovich
  • 868
  • 9
  • 13