arennuit
arennuit

Reputation: 927

Public virtual method overridden as protected in inherited class

I have a protected abstract virtual method myMethod() defined in class C. Class D inherits from C and defines myMethod(). Now class E also inherits from C and also defines myMethod(). So I have something like this:

This looks like this

class C
{
protected:
    virtual void myMethod() = 0;
}

class D : public class C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod();
}

class E : public class C
{
protected:
    void myMethod() {/*Do something else*/};
}

Now if in D::anotherMethod() I have a pointer to an object of class E then I cannot call E::myMethod(). Nothing wrong here: D and E have different hierarchies hence I cannot call E::myMethod() from D. i.e the below code does not compile which is expected:

void D::anotherMethod()
{
    E* myE = new E();

    myE->myMethod();
}

Now if I change the declaration of C and make E::myMethod() public (while keeping the overridden method in D and E protected), such as in the code below, it compiles:

class C
{
public:
    virtual void myMethod() = 0;
}

class D : public class C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod();
}

class E : public class C
{
protected:
    void myMethod() {/*Do something else*/};
}

I only changed public to protected inside C, not in the inherited classes D and E.

Does anyone know why it compiles and what is the logic behind it?

Thanks!

Antoine.

Upvotes: 3

Views: 1648

Answers (1)

Jarod42
Jarod42

Reputation: 217458

We can use C interface as it is public: E interface is protected and D can't access from E but can from base class C

As follow:

class C
{
public:
    virtual void myMethod() = 0;
};

class E : public C
{
protected:
    void myMethod() {/*Do something else*/};
};


class D : public C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod(){
        //C* myE = new E(); // does compile
        E* myE = new E(); // doesn't compile

        myE->myMethod();
    }
};

Upvotes: 2

Related Questions