Overloading virtual functions of the same name from different base classes. Is it possible? [duplicate]
Asked Answered
S

3

10

The title is probably confusing.

Suppose we have the following set up;

class A
{
public:
    virtual void fn() = 0;
};

class B
{
public:
    virtual int fn() {};
};

class C: public A, public B
{
};

Is there any way to define A::fn in class C?

Selfdetermination answered 6/9, 2011 at 11:55 Comment(0)
L
2

No. This is not possible. It will always conflict with either of the fn().

The syntax of fn() are different,

void fn();  // in A

and in B is,

int fn();  // in B

You have to make those syntax same in A and B to let C implement the fn(). Demo.

Libb answered 6/9, 2011 at 12:0 Comment(0)
C
4

There's no way in C to specify that one of the C::fn() implementations overloads A::fn() (and presumably another overloads B::fn()). What you can do, however, is introduce an intermediate class which “renames” the functions, something like:

class RemapA : public A
{
    virtual void fnInA() = 0;
public:
    virtual void fn()
    {
        fnInA();
    }
};

class RemapB : public B
{
    virtual int fnInB() = 0;
public:
    virtual int fn()
    {
        return fnInB();
    }
};

class C : public RemapA, public RemapB
{
    virtual void fnInA() { /* ... */ }
    virtual void fnInB() { /* ... */ }
    //  ...
};
Conal answered 6/9, 2011 at 12:37 Comment(0)
L
2

No. This is not possible. It will always conflict with either of the fn().

The syntax of fn() are different,

void fn();  // in A

and in B is,

int fn();  // in B

You have to make those syntax same in A and B to let C implement the fn(). Demo.

Libb answered 6/9, 2011 at 12:0 Comment(0)
O
1

You might want to read my answer to the following question: Implement two functions with the same name but different, non-covariant return types due to multiple abstract base classes In short: Yes, with some restrictions on calling it. It can be called as an A (pointer or reference) or a B (pointer or reference), but not as a C, as that would be ambiguous.

Oeflein answered 7/7, 2012 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.