Reputation: 287
I have Classes A, B. B derives from A with protected, so to enable implicit casting from B to A, I have added casting operator, but I get error when using it implicitly (everything ok when using it explicitly).
How to make this code work??
class A
{
public:
int a;
};
class B : protected A {
public:
int b;
operator const A&()const { return *this; }
};
B b;
const A& a = b; // ERROR: error C2243: 'type cast' : conversion from 'const b *' to 'const A &' exists, but is inaccessible
How to make the casting implicit?
Upvotes: 0
Views: 384
Reputation: 287
OK - so I have choosen another design - to use composition instead of inheritance. This way I can define an instance A which is protected
class B {
protected:
A a;
public
operator const A&()const { return a; }
};
B b;
const A& a = b;
Upvotes: 0
Reputation: 101
Obviously, the type conversion operator is defined in B, so it is not available for objects of type A. What you are trying to do is not possible in C++. This is because, the 'this' pointer is a constant pointer.
So, if you try writing the following code within the body of A, it will not work:
A(B* b)
{
this = b;//error, 'this' pointer is a constant pointer.
}
In other words, you cannot implicitly make a reference of type A refer to a B type object. At best, you can try a reinterpret cast and see if it works.
Upvotes: 0
Reputation: 208343
The conversion operator you provided is already implicit. The problem you face is that the compiler is seeing two different conversion sequences from B
to const A&
, the derived-to-base reference and your user provided conversion. There is an ordering on conversions, and the derived-to-base conversion is considered better than any user provided conversion, so your operator const A&() const
will not be chosen.
Just make inheritance public. You are trying to build a convoluted design that provides no benefit whatsoever. What do you want to obtain by making inheritance protected? Avoid upcasts? Why are you attempting to provide the same conversion anyway? Do you intend on only allowing half of the interface (the const
part)? Then you are not following LSP, since your derived object cannot be used as a base...
Upvotes: 2