Search code examples
c++inheritancepolymorphismoverloading

C++: Accessing Grandparent Method


Why doesn't this work, and what would be a good alternative?

class Grandparent
{
    void DoSomething( int number );
};

class Parent : Grandparent
{
};

class Child : Parent
{
    void DoSomething()
    {
        Grandparent::DoSomething( 10 ); // Does not work.
        Parent::DoSomething( 10 ); // Does not work.
    }
};

Solution

  • class Grandparent
    {
    protected:
        void DoSomething( int number );
    };
    
    class Parent : protected Grandparent
    {
    };
    
    class Child : Parent
    {
        void DoSomething()
        {
            Grandparent::DoSomething( 10 ); //Now it works
            Parent::DoSomething( 10 ); // Now it works.
        }
    };
    

    At a minimum it needs to look like that. Things are private by default when working with classes, this includes from subclasses.

    http://codepad.org/xRhc5ig4

    There is a full example that compiles and runs.