3

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::")

user1518399
  • 33
  • 1
  • 3
  • That fact that `Parent` is a subclass of `Child` does not mean it automatically generates a subclass of `Nested`. Instead, it inherits the entire nested class. And btw., why are you using both `friend`-ship and inheritance? – Fred Foo Jul 12 '12 at 09:35
  • I use friendship because "Nested" is private and I use inheritance because I want don't want to rewrite the whole "Parent" just alter that one function. – user1518399 Jul 12 '12 at 09:45

3 Answers3

10

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Does this mean that an instance of `Child` will thus have two nested classes, `Nested` and `ChildNested` – johnbakers May 25 '13 at 05:37
  • And incidentally, why is it necessary to make `Child` a `friend` if `Child` derives? I would think that a public inheritance would allow Child to access Nested fine – johnbakers May 25 '13 at 05:38
2

Basically you need to derive another class in the Child as given below and implement your virtual function there.

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

class Child : Parent 
{

    //derive a new class in the child to override the virtual function.
    class ChildNested : public Parent::Nested
    {
       void nestedfun() {std::cout << "two";}
    };
};
PermanentGuest
  • 5,213
  • 2
  • 27
  • 36
1

You can overwrite virtual function of the base class in the derived class. Inner class is a separate class. You need to create a class that will derive from your inner class. Something like that:

class Child : Parent::Nested {
  void nestedfun() {std::cout << "two";}
}
Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51