class IA
{
public:
virtual void a() = 0;
};
class A: public IA
{
public:
virtual void a()
{
}
};
class IB
{
public:
virtual void b() = 0;
};
class B: public IB, public A
{
public:
virtual void b()
{
}
};
void f(IA* p)
{
}
int main()
{
B b = B();
IB* p = &b;
f(p);
}
Is this the correct way to implement interfaces with inheritance in C++? If so, how do I get the line f(p); in my code to compile? Basically, I would like if IB could inherit from IA but this will cause problems for B.
UPDATE
What I want is for IB to include IA‘s interface, as follows. However this code wont compile since IA::a() and A::a() conflict with each other. What should I do?
class IA
{
public:
virtual void a() = 0;
};
class A: public IA
{
public:
virtual void a()
{
}
};
class IB : public IA
{
public:
virtual void b() = 0;
};
class B: public IB, public A
{
public:
virtual void b()
{
}
};
UPDATE 2
This compiles, does it look correct? Do I need all these virtuals
class IA
{
public:
virtual void a() = 0;
};
class A: virtual public IA
{
public:
virtual void a()
{
}
};
class IB: virtual public IA
{
public:
virtual void b() = 0;
};
class B: virtual public IB, public A
{
public:
virtual void b()
{
}
};
Well, this is the right way of course, but the line
f(p)should not compile as is, imagine classes that implementIB, but don’t implementIA, it’s possible, so you cannot assume that they all implementIA. If you want to assume that, you can inheritIBfromIA, but this is another design. It can be implemented like this: