I have the following three typecastings between the private inherited base class object and the child object, two of them work, but the last one doesn't. I am wondering what causes the different results.
#include<iostream>
#include <string>
using namespace std;
class test :private string
{
public:
test(string st) :string(st){}
void show();
};
void test::show()
{
cout << (string)*this << endl; // typecasting 1, works, display "abcd"
}
int main()
{
test a("abcd");
a.show();
cout << (string &)a << endl; //typecasting 2, works, display "abcd"
cout<<(string )a<<endl; //typecasting 3; error C2243: 'type cast' : conversion from 'test *' to 'const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &' exists, but is inaccessible
}
Isn't a
the same as '*this' - since both are objects? So why does No.1 work?
If it's because of scope, then why No.2 works? Could anyone please explain the mechanism behind each of them that make the difference among them?
Also, the first method seems to create a string object. In the private inherited case, base class reference can't be set to the derived class object. So how the temporary string object is created?
Thanks in advance.