开发者

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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜