If 'C' inherits from 'B' publicly, B inherits from 'A' privately, Why can't I create an object of 'A' inside 'C'? [duplicate]
Asked Answered
F

1

7

I'm using Visual C++, If I compile this code:

class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        A a{};
    }
};

I get this error:

error C2247: 'A' not accessible because 'B' uses 'private' to inherit from 'A'

I know that if I use private inheritance, Then the members of the class 'A' would be private in 'B', And inaccessible in 'C', But why can't I create an object of 'A' inside 'C'?

Freezing answered 15/2, 2020 at 10:0 Comment(0)
W
7

The problem is that the name A inside the scope of the class C is a private name.

It is a so-called injected class name.

From the C++ Standard (6.3.2 Point of declaration)

8 The point of declaration for an injected-class-name (Clause 12) is immediately following the opening brace of the class definition.

Use the following approach that is use the qualified name

class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        ::A a{};
      //^^^^^^ 
    }
};
Warfold answered 15/2, 2020 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.