Possible Duplicate:
Private virtual method in C++
If I understood correctly from this post (Private virtual method in C++), making a virtual function in a base class makes the derived classes able to override it. But it seems things stop there.
But if the base class virtual function is pure, that forces the derived classes to implement the function. Hence, a pure (public) virtual function is merely an interface. I can see a benefit here.
On the other hand, by making a base class virtual function private, only gives the derived class the ability to override the function, but I see no benefit of this. It's as if that private virtual function is not even there. The derived class obviously does not know about the existence of that virtual function in base class because its private, so is there any benefit of declaring a base class private function virtual, in term of inheritance or polymorphism?
Also, is there any situation where a base class would declare a function 'pure virtual' and 'private'?
Thank you.
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example: C++
A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.
A private virtual function can be overridden by derived classes, but can only be called from within the base class. This is actually a useful construct when you want that effect.
A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.
One benefit is in implementing the template method pattern:
class Base {
public :
void doSomething() {
doSomething1();
doSomething2();
doSomething3();
}
private:
virtual void doSomething1()=0;
virtual void doSomething2()=0;
virtual void doSomething3()=0;
};
class Derived : public Base {
private:
virtual void doSomething1() { ... }
virtual void doSomething2() { .... }
virtual void doSomething3() { .... }
}
This allows the derived classes to implement each piece of a certain logic, while the base class determines how to put these pieces together. And since the pieces don't make sense by themselves, they are declared private
and so hidden from client code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With