Search code examples
c++virtual

change from pure virtual to virtual in C++


I am having a base class that has 5 subclasses.

If in my base class I have this:

virtual CpuPort &getsecondDataPort()=0;

then this means that the method has to be implemented for all the subclasses, right?

But I do not want that, since I know that I will call that method only when I have an object of the specific subclass so I thought that I could write this instead:

virtual CpuPort &getsecondDataPort();

and implement it only in the subclass I want. But that gives me this error:

/base.cc:254: undefined reference to `vtable for BaseCPU'

and in the from the other subclasses :

undefined reference to `typeinfo for BaseCPU'

where BaseCPU is my object of the base class.

Because it is part of a bigger library (simulator actually), I want to make as fewer changes as possible. So please do not suggest something like 'define that oonly in your subclass' as I want to follow the way code is organized so far, unless this is the only way of fixing the problem.

Any idea on why that might happen?

Thanks


Solution

  • this means that the method has to be implemented for all the subclasses, right?

    Only if you want to create direct instances of those subclasses. If a subclass does not implement a pure virtual function, it will be abstract - which is allowed per se.

    But that gives me this error:

    This is because the virtual function is declared, but not defined. You have to provide a definition if the function is not pure virtual.

    In this case, you can not provide a dummy implementation that does nothing, because your function is supposed to return a reference, and flowing off the end of a value-returning function without returning anything is Undefined Behavior per Paragraph 6.6.3/2 of the C++11 Standard.

    If your base class has a data member of type CpuPort called (say) myCpuPort, on the other hand, you could do this:

    virtual CpuPort &getsecondDataPort() { return myCpuPort; }