Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing string on private std::string inheritance

Tags:

c++

I have seen this example from the book:

class Test: private std::string
{
public:
    Test():std::string("How?")
    {
    }
};

int main(int argc, char** argv)
{
    Test t;

    std::cout<<(std::string&)t<<std::endl;

    return 0;
}

I don't know how did it printed "how" when i typecasted the class name? is it because of operators? but i know that when you do private inheritance, the public and protected variables and methods will be considered "private" outside.

So my question is, how did it exactly printed "How" ?

edit :

so who is holding the string value "How" and how was it printed? Because it was printed by typecasting.

like image 939
Carlos Miguel Colanta Avatar asked Jan 09 '23 07:01

Carlos Miguel Colanta


2 Answers

This illustrates one of the dangers of the C-style cast : it's the only cast that ignores inheritance access specifiers. As you saw, the cast successfully dug out the std::string base reference, even though it was private. If you try this with a static_cast, it won't compile.

Edit :

The std::string subobject of t is holding "How", as you initialized it in Test's constructor. Casting to a reference to a base class serves to access the corresponding subobject.

like image 68
Quentin Avatar answered Jan 16 '23 04:01

Quentin


The cast (std::string&)t casts t to a reference to an instance of its base class std::string. C style casts are the only casts that can cast to an inaccessible base class. The effect is the same as with an ordinary implicit conversion to an accessible base class.

like image 41
Cheers and hth. - Alf Avatar answered Jan 16 '23 04:01

Cheers and hth. - Alf