7

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

alk3ovation
  • 1,202
  • 11
  • 15
  • 3
    Can you put the exact compiler error? Just to make sure there's nothing const-related or similar there. (by the information you describe it should work) – Shiroko Apr 27 '11 at 18:32
  • "Node is publicly derived from PCSNode"??? I guess you mean "`PCSNode` is publicly derived from `Node`" that is the same as "`Node` is a base class for `PCSNode`". Right? – Serge Dundich Apr 27 '11 at 21:37
  • PCSNode is actually the base class because it contains the pointers for the tree, Node is a transformational node that can be in a tree. – alk3ovation Jun 03 '11 at 17:07

1 Answers1

26

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
}
Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
  • What can be done in the case where the definition cannot be made available due to circular dependency issues? Can some kind of cast still be done? – Ben Farmer Mar 10 '15 at 17:23
  • There's always reintepret_cast, which works if you are casting pointers, since they are of the same size. – GolDDranks Jun 10 '15 at 12:40