I was reading about access specifiers when applying inheritance, and I know that in private inheritance
we could not cast from a derived to a base class using pointers/references.
But when I used reinterpret_cast
it worked. below is my test code:
class base {
int _a;
public:
base(int a): _a(a) {}
base(): _a(0) {}
};
class derived : private base
{
public:
derived(int b):base(b) {};
};
int main() {
derived b(25);
base &a = static_cast<base&>(b);//this line will generate a compile error
base &c = reinterpret_cast<base&>(b); //here it works
}
So my question is even doing private inheritance, why the base class would be exposed using retinterpret_cast
?
Thank you!
//EDIT 2
class base {
int _a;
public:
base(int a): _a(a) {}
base(): _a(100) {}
~base() { std::cout << "deleting base" << _a << "\n"; }
};
class derived : private base
{
public:
virtual ~derived() = default;
derived(int b):base(b) {};
};
int main() {
derived b(25);
base &c = reinterpret_cast<base&>(b);
}
//OutPut : Deleting 25