Multiply inherit from classes with conflicting function names

A

Adam

I have an unfortunate case where a single class wants to derive from two
existing classes:

struct A { virtual long fun() = 0; };
struct B { virtual bool fun() = 0; };
struct Unfortunate : public A, public B { ??? };

Is it possible to fill in the ??? here with legal code?
I need two different function bodies; A::fun and B::fun do unrelated
things.

More or less the same question with a twist: if A::fun and B::fun both
returned the same type, would it be possible to implement two functions
in C such that
C().A::fun()
and
C().B::fun()
would execute two different functions?
 
A

Alf P. Steinbach

* Adam:
I have an unfortunate case where a single class wants to derive from two
existing classes:

struct A { virtual long fun() = 0; };
struct B { virtual bool fun() = 0; };
struct Unfortunate : public A, public B { ??? };

Is it possible to fill in the ??? here with legal code?
I need two different function bodies; A::fun and B::fun do unrelated
things.

If the 'public' inheritance is intentional, and denotes IsA
relationships, then you're stuck: C++ does not allow you to overload
solely on the result type of a function, so there's no way an
Unfortunate object can be used both as an A object and as a B object.

Here's one possibility:

struct A { virtual long fun() = 0; };
struct B { virtual bool fun() = 0; };

class A_: public A
{
public:
virtual long funA() = 0;
virtual long fun() { return funA(); }
};

class B_: public B
{
public:
virtual bool funB() = 0;
virtual bool fun() { return funB(); }
};

class Unfortunate: public A_, public B_
{
public:
virtual long funA() { return 42; }
virtual bool funB() { return true; }
};

More or less the same question with a twist: if A::fun and B::fun both
returned the same type, would it be possible to implement two functions
in C such that
C().A::fun()
and
C().B::fun()
would execute two different functions?

No, neither A nor B define an implementation of fun.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,771
Messages
2,569,587
Members
45,099
Latest member
AmbrosePri
Top