SuperKogito
SuperKogito

Reputation: 2966

How to correctly write a pointer function declaration?

I am very confused about how to properly declare a pointer function. Can anyone, tell me what is the proper way to do it and correct this. Please note that the class declaration can be extended but preferably not deleted.

The following is my code and it causes the following error:

error: 'Node::Node' names the constructor, not the type

#include <iostream>

using namespace std;
class Node {
  public:
      int value;
      Node *right;
      Node *left;

      Node* find (int key);
};

Node::Node* find (int key)
{
    if (value == key)              { return this;}
    else if (value > key && right) { right->find(key); }
    else if (value < key && left)  { left->find(key); }
    else                           { return NULL;}
}

int main()
{
    Node *head  = new Node();
    Node *right = new Node ();
    Node *left  = new Node ();
    head->value  = 5;
    right->value = 3;
    left->value  = 9;

    head->right  = right;
    head->left   = left;

    Node *mm;

    mm = head->find(8);
    cout << mm->value <<endl;}

    return 0;
}

Upvotes: 0

Views: 84

Answers (3)

Ajay
Ajay

Reputation: 18421

This question isn't really about function-pointer or something related. It's just "How to implement a method outside of a class?". You have the following approach:

ReturnType CLASSNAME::METHODNAME(Any Parameters)

So, to have a method not returning:

void Node::test(){}

Returning:

int Node::test(){}

Returning a pointer:

int* Node::test(){}

Returning Node:

Node Node::test(){}

Returning a pointer to Node:

Node* Node::test(){}

Upvotes: 1

Sharath
Sharath

Reputation: 1775

The function definition should be like this.

Node* Node::find(int key)

Upvotes: 1

The name Node is in global scope and so does not need any qualification. The name of the member function find is in the scope of the class Node and thus has to be qualified:

Node* Node::find(int key) {
  //...
}

Upvotes: 1

Related Questions