Search code examples
c++overridingfriendnested-class

C++ friend, override nested class's function


I want to override a virtual function in a nested class, from a friend (+child) class. How is this possible? Here is what I tried:

class Parent {
  friend class Child;
  class Nested {
    public: virtual void nestedfunc() {std::cout << "one";}
  }
};
class Child : Parent {
  void Child::Nested::nestedfun() {std::cout << "two";}
}

But I get:

error: cannot define member function 'Parent::Nested::nestedfunc' within 'Child'

(Same error without "Child::")


Solution

  • As overrides go, you need to extend the class and then override it:

    class Parent {
      friend class Child;
      class Nested {
        public: virtual void nestedfunc() {std::cout << "one";}
      }
    };
    class Child : Parent {
      class ChildNested : Parent::Nested
      {
        public: virtual void nestedfunc() {std::cout << "two";}
      }
    }
    

    Inner classes aren't that special, they don't break the rules of inheritance or provide any special magic that would let you override a method but not derive from the class that declares it.