vize_xpft
vize_xpft

Reputation: 67

How to cast an variable with type abstract class to its subclass?

I'm writing an interface for a method.

void method(Node* node);

The interface has the code

class Node {
 public:
     virtual void init(Node* a) = 0;
};

The sub class has the code

class CNode: public Node {
 public:
     void init(Node* a);
     void init(CNode* a);
}

In the code CNode::init(Node* a), the function will try to convert a into CNode, then call CNode::init(CNode* a).

I'm trying to implement it with

void CNode::init(Node *a) {
    CNode b = dynamic_cast<CNode *>(*a);
}

However, clang reported this error

'Node' is not a pointer

How can I solve this problem?

Upvotes: 2

Views: 176

Answers (1)

John Zwinck
John Zwinck

Reputation: 249652

It should be:

void CNode::init(Node *a) {
    if (CNode *b = dynamic_cast<CNode *>(a))
        init(b);
}

Upvotes: 6

Related Questions