2

I have a class A and a class B that inherits from A. A has a foo method which I would like to override in B.

class A {
public:
    void foo();
    ...
}

class B: public A {
public:
    void foo();
    ...
}

The solution to this would of course be to define A::foo() as a virtual method, by declaring it as virtual void foo();. But the problem is that I can't do that, since the A class is defined in a third-party library so I would rather not change its code.

After some searching, I found the override keyword (so that the declaration for B::foo would be void foo() override;), but that didn't help me since that's not what override is for, override can apparently only be used on virtual methods to be sure that the method is really overriding another method and that the programmer didn't make a mistake, and it generates an error if the method isn't virtual.

My question is how can I achieve the same effect as making A::foo virtual without changing any of the code for A, but only the code for B?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 4
    If the base class is not designed to support virtual dispatch, then basically you can't, without changing the class - specifically, it had better have a virtual destructor. –  Aug 20 '17 at 14:38
  • 4
    The short answer is: you can't. C++ does not work this way. – Sam Varshavchik Aug 20 '17 at 14:42
  • 1
    @NeilButterworth What I'm planning on doing is adding `A::foo();` inside `B::foo`, so that `B::foo` calls `A::foo` and some other things that I need, so what I would like to do shouldn't really change how the base class behaves. – Donald Duck Aug 20 '17 at 14:47
  • @Donald Well, that sounds do-able, but it doesn't override anything. –  Aug 20 '17 at 14:48
  • 3
    "Override" means that when you have a pointer or reference to the base type and call the base class's function the call goes to the version of the function defined in the derived class. If that's what you want to do, you **have to** declare the base class function as `virtual`. If you want to do something else, then you're not overriding, and you need to say what it is that you want to do. – Pete Becker Aug 20 '17 at 15:10

1 Answers1

0

A bit late. But you can use std::variant and delegate methods to the two classes A and B according to the concrete type.

If your compiler is not that up to date, use a tagged union instead.

Seideun
  • 153
  • 2
  • 7