Jason Hu
Jason Hu

Reputation: 1267

C++ recursive pointer function calls

I currently have a base class Expr and some derivatives like AddExpr, MultExpr and NumExpr. I am trying to overload a general print() function that recursively calls the print() function of its members which are pointers to other Expr objects.

//Addition Expression
AddExpr::AddExpr( Expr* l, Expr* r ) {
    left = l;
    right = r;
}
string AddExpr::print() {
    string s;
    stringstream out;
    out << "(+" << left->print() << right->print() << ")";
    s = out.str();
}

NumExpr::NumExpr( string n ) {
    number = atoi( n.c_str() );
}
string NumExpr::print() {
    string s;
    stringstream out;
    out << number;
    s = out.str();
    return s;
}

So ultimately I want the add expression to print out a ( number + number ) if the left and right pointers are numbers, ( expression + number ), ( expression + expression ), etc. by recursively calling the print() function.

However I don't think I'm approaching this correctly as I am getting jumbled output :( I am not too familiar with pass by pointer and pass by reference, however every post that I have gone through with similar question are not quite relevant to my situation.

Here's a debug sample for calling the functions:

NumExpr* left = new NumExpr("1");
cout << left->print() << endl;
NumExpr* right = new NumExpr("2");
cout << right->print() << endl;
AddExpr* temp = new AddExpr( left, right );
cout << temp->print() << endl;
Expr* temp2 = temp;
cout << temp2->print() << endl; 

This will print out 1 and 2 but has the problem on the AddExpr.

Any help is appreciated!

EDIT: the header for my expression classes:

class Expr {
    public:
        virtual string name();
        virtual string print();
};

class AddExpr : public Expr {
    public:
        AddExpr(Expr* l, Expr* r);
        string print();
    private:
        Expr* left;
        Expr* right;
};

class NumExpr : public Expr {
    public:
        NumExpr( string v );
        string print();
    private:
        int number;
};

Upvotes: 0

Views: 1084

Answers (2)

Edward Loper
Edward Loper

Reputation: 15944

I see two problems with your AddExpr::print() method:

  1. It doesn't actually return anything. You should have at least gotten a compiler warning, if not an error, for this.

  2. It doesn't put any space between left and right.

Try this:

string AddExpr::print() {
    string s;
    stringstream out;
    out << "(+" << left->print() << " " << right->print() << ")";
    s = out.str();
    return s;
}

Though actually, it would be better to do the following -- no need to create an explicit string variable:

string AddExpr::print() {
    stringstream out;
    out << "(+" << left->print() << " " << right->print() << ")";
    return out.str();
}

Upvotes: 2

Oswald
Oswald

Reputation: 31675

AddExpr::print() does not return any value.

Upvotes: 4

Related Questions