Vladimir Yanakiev Vladimir Yanakiev - 1 month ago 11
C++ Question

default beahviour implemented to pure virtual function

I've read that Scott Meyers suggest default behaviour to virutal functions to be:

class base
{
.....
protected:
void vfDefault();
public:
virtual void vf() =0;
};


when it is implemented in derived class

class d1:public base
{
virtual vf()
{
vfDefault();
....
}
};


But it is possible also to implement the pure virtual function and use it as default behaviour:

class base
{
...
public:
virtual void vf() =0;
}
void base::vf()
{
.....
};


when it is implemented in derived class

class d1:public base
{
virtual vf()
{
base::vf();
....
}
};


is there any disadvatage of using pure virtual function inmplementation for default behaviour?

Answer

Note that vfDefault() and vf() have different access specifiers. Everybody can call base::vf(), including directly calling base implementation. But only children of the base can call vfDefault(). So if you implement default behaviour as a separate protected function you can be sure that external code can't call it directly.