Question

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

Was it helpful?

Solution

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top