Search code examples
c++virtualprivate-members

How to implement a private virtual function within derived classes?


I know why I want to use private virtual functions, but how exactly can I implement them?

For example:

class Base{
[...]
private:
 virtual void func() = 0;
[...]
};

class Derived1: public Base{
  void func() 
  { //short implementation is ok here
  }
};

class Derived2: public Base{
  void func(); //long implementation elsewhere (in cpp file)
};

[...] 

void Derived2::func()
{ //long implementation 
}

The first version is ok but not always possible. Isn't the second version simply name hiding? How do you define the Base::func() of Derived2, if you cannot do it within the class declaration of Dereived2?

Thanks


Solution

  • How do you define the Base::func() of Derived2, if you cannot do it within the class declaration of Dereived2?

    You don't define "Base::func() of Derived2" (whatever this might be), you define Derived2::func(). This compiles just fine for me:

    #include <iostream>
    
    class Base{
    private:
     virtual void foo() = 0;
    public:
      void bar() {foo();}
    };
    
    class Derived: public Base{
      void foo();
    };
    
    void Derived::foo()
    {
       std::cout << "inside of 'Derived1::foo()'\n";
    }
    
    int main()
    {
      Derived d;
      Base& b = d;
      b.bar();
      return 0;
    }
    

    What's your problem with it?