Is it possible to getting rid of error C2243?
class B {};
class D : protected B {};
D d;
B *p = &d; // conversion from 'D *' to 'B &' exists, but is inaccessible
I had this error in my app and at the end I've managed to compile it by making an explicit conversion:
D d;
B *p = (B*)&d;
I can't understand why by making class D inherited protected from B makes the implicit conversion inaccessible.
I tried to avoid explicit conversion by creating a operator B() in class D in order to make the conversion accessible:
class B {};
class D : protected B
{
public:
operator B() {return *this;}
};
But there is no way.
Any other solution to avoid explicit conversion?
If you want to allow conversion, you should be using public inheritance.
Using protected or private inheritance, you are declaring that the fact that the derived type inherits from the base class is a detail that should not be visible from the outside: that's why you are getting that error.
You should regard non-public inheritance only as a form of composition with the added possibility to override methods.
Because protected
and private
inheritance are not is-a
relationship, they are just syntax sugar for composition. Your classes can be rewritten exactly like this, but you lose the convenience of letting the compiler define b
for you, and using b members directly instead of referring to it explicitly :
class D
{
protected:
B b;
};
For the second point of your question:
operator B() {return *this;}
This line has to do with B
and D
. D* and B* are totally different from B and D though they are pointers to them! to cast pointers, you could reinterpret the pointer:
B *p = reinterpret_cast<B*>(&d); // TOTALLY WRONG, although it compiles :)
Don't do the above line! I think you might give us more info of what you are trying to achieve.
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