Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a static_cast from a Pointer to Base to a Pointer to Derived "invalid?"

So I have this code:

Node* SceneGraph::getFirstNodeWithGroupID(const int groupID)
{
    return static_cast<Node*>(mTree->getNode(groupID));
}

mTree->getNode(groupID) returns a PCSNode*. Node is publicly derived from PCSNode.

All of the docs I've found on static_cast say something to this effect: "The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class."

Yet, XCode's (GCC) compiler says that the static_cast is from PCSNode* to Node* is invalid and not allowed.

Any reason why this is? When I switch it to a C-style cast, there are no complaints from the compiler.

Thanks.

UPDATE: Even though the question was answered, I'll post the compiler error for completeness in case anyone else has the same problem:

error: Semantic Issue: Static_cast from 'PCSNode *' to 'Node *' is not allowed

like image 446
alk3ovation Avatar asked Apr 27 '11 18:04

alk3ovation


1 Answers

The reason is most likely that the definition of Node is not visible to the compiler (e.g., it may have been only forward-declared: class Node;).

Self-contained example:

class Base {};

class Derived; // forward declaration

Base b;

Derived * foo() {
    return static_cast<Derived*>( &b ); // error: invalid cast
}

class Derived : public Base {}; // full definition

Derived * foo2() {
    return static_cast<Derived*>( &b ); // ok
}
like image 143
Marc Mutz - mmutz Avatar answered Sep 28 '22 08:09

Marc Mutz - mmutz