How to call a member function of an object using that object's pointer?

77 views Asked by At

I have a Node object that has a public member function. When I have a pointer (or double pointer) in this case pointing to the original object, how do I call the member function?

Here is the member function in the Node class:

class Node {
public:
    ...
    int setMarked();
    ...
private:
    ...
    int marked;
    ...
};

And here is where I am trying to call that function:

Node **s;
s = &startNode; //startNode is the original pointer to the Node I want to "mark"
q.push(**s); //this is a little unrelated, but showing that it does work to push the original object onto the queue.
**s.setMarked(); //This is where I am getting the error and where most of the question lies.

And just in case it matters, the .setMarked() function looks like this:

int Node::setMarked() {
    marked = 1;
    return marked;
}
1

There are 1 answers

6
nneonneo On BEST ANSWER

Dereference it twice first. Note that * binds less tightly than . or ->, so you need parens:

(**s).setMarked();

Or,

(*s)->setMarked();

In your original code, the compiler was seeing the equivalent of

**(s.setMarked());

which is why it wasn't working.