2

I am trying to create a pointer to a class as follows.

ASTNode* pAssign = new ASTAssignmentNode();

However, pAssign does not consist of the variables defined in class ASTAssignmentNode . Am I missing out on something here? How can I access the variables defined in ASTAssignmentNode() ? ASTAssignmentNode() inherits from ASTStatementNode() which inherits from ASTNode().

When writing pAssign->variable (which is declared in ASTAssignmentNode()) an error occurs "pAssign does not contain definition for member variable"

I am not experienced in C++.

Would appreciate any help.

Techworld
  • 141
  • 1
  • 12

3 Answers3

1

You should use ASTAssignmentNode* pAssign instead. If you're doing this for a class assignment and they give you files you aren't supposed to modify that make you utilize ASTNode*, ask your TA about it because I've been in that situation and there should be workarounds you can use but it will differ from different assignments.

Cameron637
  • 1,699
  • 13
  • 21
1

Try casting to access variables belonging to ASTAssignmentNode class

((ASTAssignmentNode* ) pAssign)->variable

What I have used is called a regular cast. You may also use static cast or dynamic cast has mentioned by M.M. If you want a detailed breakdown of which type of cast you need, check out a post here.

As long as you are certain ASTAssignmentNode is a child of ASTNode there should be no implications.

When you cast ASTAssignmentNode to ASTNode it will only contain the class definition for ASTNode and it knows nothing about ASTAssignmentNode. That is why you need to cast it back.

An exception to this are virtual functions. Virtual functions call the child class implementation if they exist.

Community
  • 1
  • 1
Striker
  • 507
  • 4
  • 11
0

Since pAssign is a pointer to the base class, you will need to cast it to the derived class, ASTAssignmentNode. Preferably with a c++ dynamic_cast.

dynamic_cast<ASTAssignmentNode*>(pAssign)->variable
Mike M
  • 1
  • 3