Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast Derived*const to Base*const

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.

like image 556
parallel Avatar asked Oct 16 '10 20:10

parallel


2 Answers

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.

like image 59
parallel Avatar answered Oct 01 '22 08:10

parallel


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.

like image 40
Oliver Charlesworth Avatar answered Oct 01 '22 07:10

Oliver Charlesworth