Re: C2614: Inheritance question
Jack wrote:
class CPerson : public CPathfinder
{
bool Create(...);
...
};
class CSupervisor : public CPerson
{
virtual bool Create (...);
};
One thing up front: I will assume that the parameters to Create() are the
same in both cases, because if not, you have in fact an overloaded
function.
In this case, should I put the implementation code in CPerson with each
function declared as virtual and in CSupervisor as non-virtual, or the
other way round, implement code in CSupervisor and declared the derived
methods as virtual while CPerson as non-virtual (illustrated in the above
snippet). I tried the later method but with no errors reported, so I
assumed that was correct. But just in doubt if my design is correct or
not?
Firstly, your design won't do what you probably want. Consider this code:
CSupervisor sv;
sv.Create();
This will call CSupervisor::Create(). However, consider this snippet:
CPerson& p = sv;
p.Create();
This will call CPerson::Create() and not the virtual function from
CSupervisor. If you had put a 'virtual' into the baseclass, this would have
called the derived class' version of Create(). Note that you can only add
a 'virtual' in derived classes and not remove it. If your derived class
doesn't have a 'virtual' the function is still virtual if the baseclass has
it!
Now, generally, you define an interface in the baseclass:
struct CPerson {
bool Create(...);
};
In order to allow derived classes to implement/override this, you need to
declare this function virtual:
struct CPerson {
virtual bool Create(...);
};
If there is no sensible default-implementation in the baseclass, you make it
a pure virtual function:
struct CPerson {
virtual bool Create(...) = 0;
};
Every derived concrete class then has to implement this function.
Uli