Inheritance question

H

He Shiming

Hi,

I've got a question regarding class inheritance. The following code
reproduces the problem I'm dealing with:

class IBase
{
public:
virtual void Method(void)=0;
};

class IDefinition : public IBase
{
};

class CCoImpl
{
public:
void Method(void){}
};

class CImpl : public IDefinition, public CCoImpl
{
};

In the above 4 classes, IBase and IDefinition are both abstract classes.
CCoImpl contains a non-virtual method (actual implementation). CImpl is
derived from both IDefinition and CCoImpl. But when I try to initiate a new
instance of CImpl, the compiler complains about that CImpl is an abstract
class because void IBase::Method(void); isn't defined.

Why is that? CImpl is derived from CCoImpl, doesn't it inherit the "void
Method(void);" method from CCoImpl? If it does, this method should be
implemented and CImpl shouldn't be an abstract class.

Given that IBase and IDefinition can't be changed, how do I create a CImpl
class that uses the "Method(void);" implementation from CCoImpl?

Thanks,
 
P

Phil Staite

He Shiming said:
Hi,

I've got a question regarding class inheritance. The following code
reproduces the problem I'm dealing with:

class IBase
{
public:
virtual void Method(void)=0;
};

class IDefinition : public IBase
{
};

class CCoImpl
{
public:
void Method(void){}
};

class CImpl : public IDefinition, public CCoImpl
{
};

In the above 4 classes, IBase and IDefinition are both abstract classes.
CCoImpl contains a non-virtual method (actual implementation). CImpl is
derived from both IDefinition and CCoImpl. But when I try to initiate a new
instance of CImpl, the compiler complains about that CImpl is an abstract
class because void IBase::Method(void); isn't defined.

Why is that? CImpl is derived from CCoImpl, doesn't it inherit the "void
Method(void);" method from CCoImpl? If it does, this method should be
implemented and CImpl shouldn't be an abstract class.

No, you can't "implement it sideways" like that. CImpl does not have an
implementation of Method() - hence it is abstract. You could try:

class CImpl : public IDefinition, public CCoImpl
{
public:
virtual void Method() { CCoImpl::Method(); }
};

This provides an implementation in the hierarchy so that the class is no
longer abstract. It "wires through" to one of it's base class'
implementation. A little messy IMHO, but should work.
 

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,968
Messages
2,570,150
Members
46,696
Latest member
BarbraOLog

Latest Threads

Top