The code is evaluating a expression tree.
My issue is on line 57 when I try to dynamically allocate an array to be used as the nodes in the expression tree, the compiler gives the following error:
tree.cpp(58): error: no suitable constructor exists to convert from "ExprNode *" to "ExprNode"
pN[0] = new ExprNode('+', new ExprNode(5), new ExprNode(6));

What do I need to change?

Thanks.

#include <cstdlib>  // for NULL
#include <iostream>
using namespace std;

//====================================== class ExprNode
class ExprNode {
 public:
    ExprNode(){};
    ExprNode(char oper, ExprNode* left, ExprNode* right);
    ExprNode(int val);
    int eval() const; // Evaluate expr tree. Return result.
    
 private:
    char      _op;    // one of +, -, *, /, #
    int       _value; // integer value used for constants.
    ExprNode* _left;  // left subtree
    ExprNode* _right; // right subtree
};
//============================================= ExprNode constructor
    // Constructs node for a binary operator.
ExprNode::ExprNode(char oper, ExprNode* left, ExprNode* right) {
    _op    = oper;
    _left  = left;
    _right = right;
}
   
//============================================== ExprNode constructor
    // Constructs a node for an integer constant
ExprNode::ExprNode(int v) {
    _op    = '#';
    _value = v;
    _left  = NULL;
    _right = NULL;
}

//===================================================== ExprNode::eval
int ExprNode::eval() const {
    // Recursively evaluate expression tree and return result.
    int result;
    switch (_op) {
        case '+': 
                result = _left->eval() + _right->eval();
                break;
        case '-': 
                result = _left->eval() - _right->eval();
                break;
        case '#': 
                result = _value;  // an integer constant
                break;
     }
     return result;
}

//============================================================== main
int main() {
    // Example expression and evaluation.
    ExprNode* pN = new ExprNode[2];
    pN[0] = new ExprNode('+', new ExprNode(5), new ExprNode(6));
    pN[1] = new ExprNode('-', pN[0], new ExprNode(2));
    cout << pN[1]->eval() << endl;
   delete [] pN; 
    
    return 0;
}

The variable PN is a pointer (ExprNode*) and the PN[0] will be of type ExprNode and not ExprNode*. Thats why the pointer allocated after New cannot match that type to ExprNode.

ok, so how do I fix it, how do I need to declare pN to make this work?

How do I declare it so that I can dynamically expended as an array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.