简体   繁体   中英

Override a non-virtual method in C++

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM