I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » Tutorials » C & C++ » Advanced »

private virtual Functions

CodeCogs\′s Photo
3 Dec 07, 9:17AM
private virtual Functions
Private virtual functions seem strange at first, and can be confusing, hence why many developers recommend that they are not used too often - if at all.

They are handy when functionality must be completely specific to a class, and therefore not callable from a derived class, even when a pointer to a base class is being used.

Consider these two classes:
class Parent
{
public:
  void Bar() {
    this->Whoami();
  }
 
private:
  virtual void Whoami() { 
    std::cout << "Parent::Foo" <<std::endl;
  }
};
 
class Child : public Parent
{
private:
   void Whoami() {      // virtual by default
    std::cout << "Child::Foo" <<std::endl;
  }
};

Now in this example, we create an instant of Child and assign to a Parent pointer:
int main()
{
  Parent* parent = new Child();
  parent->Bar();
  return 0;
}
Output:
Child::Foo
Currently you need to be logged in to leave a message.