Re: Virtual private member functions
On 28 Mar, 08:27, "v4vijayakumar" <vijayakumar.subbu...@gmail.com>
wrote:
On Mar 28, 11:05 am, "Salt_Peter" <pj_h...@yahoo.com> wrote:
On Mar 28, 12:50 am, "v4vijayakumar" <vijayakumar.subbu...@gmail.com>
wrote:
Why we need "virtual private member functions"? Why it is not an
(compile time) error?
Why should it be a compile time error? Private has to do with
accessibility - completely unrelated to whether its virtual or not.
What is preventing a public member function from calling a virtual
private member function?
Consider NVI (non-virtual interface) Idiom which does exactly that.
The non-virtual function is the accessible interface and the private
virtual function is the hidden worker-bee.
Calling virtual private member function is anyway different from
calling non-virtual private member?
No, consider this for example:
class Foo
{
public:
virtual void foo() { /* do stuff */ }
};
int main()
{
Foo f;
f.foo();
}
Here we call the virtual member function foo() and the same thing
happens as if the method was not virtual. The fact that the method is
private means that derived classes can't call it whenever it want,
only through the methods in the base-class that calls it (of course it
can always call on it's own implementation of the private function,
see Craig Scott's post for more on that).
Virtual only comes into play when using inheritance and only if the
derived class decides to overload the methods, consider this:
#include <iostream>
struct Base
{
virtual void foo() { std::cout << "Base\n"; }
};
struct Derived1 : public Base
{
};
struct Derived2 : public Derived1
{
void foo() { std::cout << "Derived2\n"; }
};
int main()
{
Base b;
b.foo();
std::cout << "\n";
Derived1 d1;
d1.foo();
std::cout << "\n";
Derived2 d2;
d2.foo();
}
virtual keyword has nothing to
do with private access specifier. right?
Right.
--
Erik Wikstr=F6m