Edit - Put the question into context a bit more.
Given:
struct Base
{
...
};
struct Derived : public Base
{
...
};
class Alice
{
Alice(Base *const _a);
...
};
class Bob : public Alice
{
Bob(Derived *const _a);
...
};
When I try to implement
Bob::Bob(Derived *const _d) : Alice(static_cast<Base*const>(_d)) { }
it does not work. a const_cast
doesn't make sense to me as I don't want to change the constness, and I'm not changing what I'm pointing to, so why then does g++ tell me
invalid static_cast from type ‘Derived* const’ to type ‘Base* const’
? If I leave out the cast, it says
no matching function for call to ‘Alice::Alice(Derived* const)’
If anyone could shed any light on this It'd be much appreciated.
The problem was that Derived was an incomplete type, i.e. forward declared. I'm afraid I've been giving everyone a hard time :( The answer popped up when Kiril Kirow proposed using a dynamic-cast, upon which g++ spat out this slightly more helpful error:
error: cannot dynamic_cast ‘_d’ (of type ‘struct Derived* const’) to type ‘struct Base* const’ (source is a pointer to incomplete type)
Unfortunately, I had forward declared Derived, but I hadn't realized it was relevant, and it was hidden several headers further down, which would have had me posting too much code here. Sorry everyone, but I hope this at least helps somebody else later.
You don't need any cast at all. You have const pointers, not pointers to const objects. And it's legal to assign the address of a derived object to a pointer-to-base without a cast.
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