0

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.

2 Answers2

1

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.
        }
    };
  • "*implicit `public` because C is struct but not class*/" is a tiny bit wrong. `C` is a class. `struct` and `class` are just two keywords to define a class. Though, yes, because you used `struct` the class default visibility is public – 463035818_is_not_an_ai Sep 28 '22 at 11:52
  • 1
    So, you mean, it's not because it's to cast C to A (skip B), just because it's outside of C, correct? – Home of the Brave Sep 29 '22 at 04:01
  • The cast must be inside of struct C visability to be correct. If inheritance A -> B was `public` then we could cast outside. Lasty, if inheritance A -> B was `private` then cast C -> A might be accessed in B visibility only. – Andrey Korostin Sep 29 '22 at 06:59
  • 1
    Are the below two equivalent for this case? static_cast(static_cast(tc)) and static_cast(tc) – Home of the Brave Sep 29 '22 at 09:34
  • Yes, even if you have reloaded the cast operator С->A. When you have `tc` object with one field 'c', it has technically a more field of its parent B type which also has `b` and a field of its parent A type which eventually has one 'a'. When you do `static_cast`, you just uses the `lvalue` reference (in our case) to the particular parent. – Andrey Korostin Sep 29 '22 at 10:57
  • OK, so you were saying it's safe to static_cast to the parent's parent, thank you. – Home of the Brave Sep 29 '22 at 13:24
0

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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82