Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of error C2243

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?

like image 689
Lucas Ayala Avatar asked Sep 24 '09 13:09

Lucas Ayala


2 Answers

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.

like image 121
Paolo Tedesco Avatar answered Oct 12 '22 23:10

Paolo Tedesco


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.

like image 26
Khaled Alshaya Avatar answered Oct 13 '22 01:10

Khaled Alshaya