Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'?

like image 488
StackExchange123 Avatar asked Feb 15 '20 10:02

StackExchange123


People also ask

What happens when a class is inherited as private?

With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.

Why multiple inheritance in C# is not possible?

C# compiler is designed not to support multiple inheritence because it causes ambiguity of methods from different base class. This is Cause by diamond Shape problems of two classes If two classes B and C inherit from A, and class D inherits from both B and C.

Does the order of inheritance matter if a class inherits from multiple classes?

Yes, you can do multiple inheritance. please note the order of class in ExampleSimMod matters.

Can you inherit private members of a class C++?

A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares. Yes, you could manipulate the private data in a hackish, non-portable way using this and offsetting accordingly.


1 Answers

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{};
      //^^^^^^ 
    }
};
like image 103
Vlad from Moscow Avatar answered Sep 24 '22 23:09

Vlad from Moscow