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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With