vendredi 6 septembre 2019

Shouldn't access to private types be prohibited?

Consider this code:

class A
{
    struct B {};
    std::vector<B> _vec;

public:
    const std::vector<B>& get() const { return _vec; }
};

Note that B is private within class A. The above code compiles, but when calling get() from outside class A, it does not:

const std::vector<A::B>& vec = get(); // does not compile

Indeed, A::B is private. However, from C++11 on, you could simply do this:

const auto& vec = get();

which works perfectly.

For the same reason as above, you cannot do the following:

A::B obj; 

But, since there is a public getter, you can deduce the type from that getter function. In this particular case, one could do:

using B = std::decay<decltype(C{}.get())>::type::value_type;
B obj;

Questions

I'm not sure how to formulate my questions. It seems strange to me that, from C++11 on, we actually can instantiate A::B being the latter private. And even more, I think it's strange we can call const auto& get(). Is there any explanation for this? Wouldn't it be better not be allowed doing this? Should I declare A::B public? I feel like it doesn't make sense to declare it private if you need a getter function like the one in the above code.

Aucun commentaire:

Enregistrer un commentaire