Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Visual Studio compiler allow violation of private inheritance in this example?

I found very strange behavior of std::unique_ptr in Visual Studio 2013 and 2017. Let's consider an example:

class Base 
{
public:
    virtual ~Base() = default;
    virtual void Foo() = 0;
};

class Derived : private Base 
{
public:
    void Foo() override
    {
        std::cout << "Foo";
    }
};

void Foo(std::unique_ptr<Base> a)
{
    a->Foo();
}

Foo(std::unique_ptr<Base>(new Derived())); // Compiles

Note that inheritance is private. This example compiles only on Visual Studio. Moreover, the virtual function call works because it is public inheritance. So we have encapsulation violation since the cast from Derived to Base should be inaccessible. Can anybody explain why Visual Studio allows this? Is it a known issue?

The line below doesn't compile for reasonable causes. The only difference between the first and second usages is in the second, the named object B is created.

std::unique_ptr<Base> B(new Derived()); // Doesn't compile

Is it related somehow with this issue which still isn't fixed?

like image 910
Viktor Avatar asked Apr 20 '17 20:04

Viktor


1 Answers

This is fixed in cl version 19.15.26726 (VS 2017 v15.9.0-pre.1.0):

Foo(std::unique_ptr<Base>(new Derived()));

gives

error C2243: 'type cast': conversion from 'Derived *' to 'Base *' exists, but is inaccessible
like image 120
Swordfish Avatar answered Oct 23 '22 13:10

Swordfish