Peter Stewart
Peter Stewart

Reputation: 3017

How do I use "this" in a member function?

I've written a member function of class Node to read a tree of Nodes in postfix order.

It will be called by the Node instance which is the root node of the tree.

So: N.postfix();

these appear to be illeagal:

*this->left.postfix();
*this->right.postfix();

What is the proper way to do this?

class Node
{
public:
    const char *cargo; 
    int depth; 
    Node *left; 
    Node *right

void Node::postfix()
{
    if (this==__nullptr)
    {
        return;
    }
    else
    {
        *this->left.postfix();
        *this->right.postfix();
        out<<*this->cargo<<"\n";
        return;
    }
};

Upvotes: 1

Views: 277

Answers (3)

Andy White
Andy White

Reputation: 88475

The -> operator dereferences a pointer, so the extra * will cause problems. You can either do this:

this->left->postfix();

Or this:

(*this).left->postfix();

Upvotes: 6

Edward Strange
Edward Strange

Reputation: 40895


*this->left.postfix();

"Dereference the return value of calling postfix() on the 'left' member variable of this."


this->left->postfix();
//or
(*this->left).postfix();

"Call postfix() on the dereferenced 'left' member variable of this."

Upvotes: 1

James McNellis
James McNellis

Reputation: 355347

In a member function, you don't generally need to use this to access class members; you can simply use:

left->postfix();

etc.

If you have function parameters or other local variables that have the same name as a class member variable, you can use this to refer to the member variable, e.g.,

this->left->postfix();

The reason that your code is illegal is that it does not correctly treat left as a pointer. You need to dereference left using -> in order to access its members, as shown in the correct code here. (You could also use the equivalent (*left).postfix(), but that just makes you use more parentheses for no real benefit.)

The use of the indirection operator * at the start of the expression is also incorrect, because it is applied to the result of postfix() (i.e., it dereferences whatever is returned by postfix()). postfix() doesn't return anything, so it's an error. It is important to remember that the . and -> operators both have higher precedence than *.

Upvotes: 10

Related Questions