Reputation: 243
I have a bit of a problem with multiple inheritances. I have a class C that has two base classes, A and B. A is the main base class and B provides a specialization. However, B needs to be able to call a method that is part of A.
My question is, how can I expose A.foo() to B so that it can be called? I've been googling and reading up like crazy but I can't find anything that works for my scenario. I tried template classes, but that opened up another can of worms. I tried all sorts of virtual functions but they all caused Linker errors at best.
This here is essentially what I want to be able to do…
class A
{
public:
void foo() { std::cout << "Hello there!"; }
};
class B
{
public:
void bar() { foo(); } // Call A::foo() here somehow
};
class C : public A, public B
{
};
int main( void )
{
C _test;
_test.bar();
}
Does anyone have any pointers for me how I would go about this? I also tried using another class that A and B both derive from and then using virtual inheritance and sister classes, but I could not get that to work either.
class Z
{
public:
virtual void foo()=0;
};
class A : public Z
{
public:
void foo() { std::cout << "Hello there!"; }
};
class B : public Z
{
public:
void bar() { foo(); }
};
class C : public A, public B
{
public:
// virtual void foo();
};
int main( void )
{
C _test;
_test.bar();
}
Any suggestions would be really appreciated because this is a major feature I need to implement… somehow. :)
Upvotes: 0
Views: 1274
Reputation: 243
Here is the implementation, as suggested by Sam Varshavchik. It is doesn't require an additional base class, so it is a bit leaner and works perfectly fine.
class A
{
public:
void foo() { std::cout << "Hello there!"; }
};
class B
{
public:
virtual void foo() = 0;
void bar() { foo(); }
};
class C : public A, public B
{
public:
void foo() { A::foo(); }
};
int main(int argc, const char * argv[])
{
C _test;
_test.bar();
}
Upvotes: 1
Reputation: 5920
A::foo()
is a class member function. To call it you either must have a class instance pointer, or make it static. If B
must call A
methods, perhaps it should be derived from A
. Other solution is reworking your entire class hierarchy, to move function call to the class, derived from A
and B
. Also you could pass A
pointer to the B
constructor to call it from there.
Upvotes: 0