Cast Derived * const to Base * const

Change Put the question in context a little 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)) { }

he does not work. a const_castdoesn't make sense to me, because I don't want to change the constant, and I don't change what I'm pointing to, so why does g ++ tell me

invalid static_cast from type ‘Derived* const’ to type ‘Base* const

? If I refuse the cast, he will say

no matching function for call to ‘Alice::Alice(Derived* const)’

If anyone could shed light on this, it would be very grateful.

+5
source share
7 answers

The problem was that Derived was an incomplete type, i.e. announced. I'm afraid I always gave everyone :( The answer came when Kirill Kirov suggested using a dynamic cast, on which g ++ spat out this slightly more useful error:

error: cannot dynamic_cast ‘_d’ (of type ‘struct Derived* const’) to type ‘struct Base* const’ (source is a pointer to incomplete type)

, Derived, , , , . , , - .

+5

. , const. .

+1

. , , ? , .

,

class Derived : ***public*** Base {...}

?
, , ? ...

+1

g++ 4.4.3, :

#include <iostream>

struct Base
{
    Base()
    {
    }
};

struct Derived : public Base
{
    Derived() {}
};

class Alice
{
public:
    Alice( Base *const _a )
    {
        std::cout << "Alice::Alice" << std::endl;
    }
};

class Bob : public Alice
{
public:
    Bob(Derived *const _a) 
        : Alice( static_cast< Base * const >( _a ) )
    {
        std::cout << "Bob::Bob" << std::endl;
    }
};

int main()
{
    Derived* pDer = new Derived();
    Bob b( pDer );
    return 0;
}
+1

Alice Base. Alice, Base*.

, , const.

hth.,

0

, Alice::Alice Alice. Bob Alice::Alice.

. static_cast . .

static_cast, , , const . const , .

Why your compiler produces these strange error messages is not clear to me. I suspect the code you entered is fake.

0
source

While I'm not sure (there is too little context), I think that you could mean Base const * and Derived const * .

Base const * is a pointer to a constant base object. Base * const - a constant pointer to a modifiable base object.

0
source

All Articles