Home > Mobile >  static_cast to the base of base class with protected inheritance
static_cast to the base of base class with protected inheritance

Time:09-28

I don't quite understand why below code is not legal.

struct A {
    int a;
};

struct B : protected A {
    int b;
};

struct C : B {
    int c;
} tc;

const A &ra = static_cast<A &>(tc);

Could someone help to explain it? Thank you very much.

CodePudding user response:

The public, protected and private specifiers let access in different-wide areas. You can access protected members only in your class functions or its heirs.

For example that code works:

    struct A {
        int a;
    };
    
    struct B : protected A {
        int b;
    };
    
    struct C : /*implicit `public` because C is struct but not class*/ B {
        int c;
        
        void foo(C &tc)
        {
            const A &ra = static_cast<A &>(tc);
            // Because `foo` can access to A instead of outside code like yours.
        }
    };

CodePudding user response:

Much like protected members, the inheritance is only known to B and its descendants, not to anyone else.
If this were legal, protected inheritance would be pretty pointless since anyone could just cast it away.

  •  Tags:  
  • c
  • Related