user3369592
user3369592

Reputation: 1447

function without a parameter c++

I want to understand how to write the getheight function without the parameter and it can still work.

my node.h file

Node();
~Node();

 int getHeight(Node* node);
//int getHeight(); without a parameter but those two can perform the same work

 int data;
 int height;
 Node* left;
 Node* right;

node.cpp:

   int node::height(Node *N){
   if (N == NULL)
     return 0;
   return N->height;
  }

//if I do not put the Node pointer into this function as a parameter, how should I write this function?
int node::height(){}

Upvotes: 0

Views: 2346

Answers (3)

pipja
pipja

Reputation: 181

I think conceptually you are misunderstanding something here.

From an OOP perspective, "what" are you trying to get the height of?

For your first function "Node *N" parameter is the object.

Now when you want to take out the parameter from the function call and declaration, it has to work with either an entirely arbitrary "height" that you give out, or you need to put getheight() as a member of the Node class in order to return the Node's height.

Upvotes: 1

Keith
Keith

Reputation: 6834

[ This may not be your issue, but too long for a comment.]

When trying to write:

int node::height(){}

You may have tried:

int node::height(){ return height;}

This of course gives a compile error. One means to return the value of the height member, but actually return the pointer to the member function itself.

You can write:

int node::height(){ return this->height;}

You can also by naming the method and data differently.

This is why getHeight and setHeight are often used. Some do prefer the convention that the member access method is height, so rename the member data to int height_ or some such.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110728

Since getHeight is a member of Node, it has access to the Node object's members. You can just return height;. This is the same as doing return this->height;.

Of course, they don't perform the "same work". One returns the height of a Node passed by pointer as an argument, while the other returns the height of this. In fact, you don't seem to have a good reason for having the version that takes a pointer at all. It especially should not be a member function, because it doesn't depend on the state of this. If you really wanted a function with such a signature, I suggest making it a non-member function that uses the member getHeight:

int getHeight(Node *N) {
  if (N == NULL)
    return 0;
  return N->getHeight();
}

And if the only reason you are returning 0 when receiving a null pointer is to avoid runtime errors, I suggest making the function take a reference instead:

int getHeight(Node& N) {
  return N.getHeight();
}

Upvotes: 1

Related Questions