Ben
Ben

Reputation: 563

C++ call class method from within class

I have a class that implements a linked list. The class has a find() method which finds a value if it exists in the linked list. I have another method add() which adds a node, but ONLY if that value contained in that node does NOT already exist in the list.

So what I want to do in my add() function is use my find method instead of testing for an existing value since that'd be like implementing it a second time. My question is, how can I call the find method from within another method in that class?

I tried calling this.find(x)

But that gave me errors.

Here is what some of my code looks like:

// main function
  SLList<int>list;
  list.add(20);
  list.add(14);

// SLList.h (interface and implementation)

template<typename T>
bool SLList<T>::find(const T& val) const {
  // finds value
}


template<typename T>
void SLList<T>::add(const T& x) {
  bool found = this.find(x);
  if (found) return false;

  // goes on to add a node in the Singly Linked list (SLList)
}

So Like I said, I want to be able to call the find method from within another method in that class, and I thought all I'd have to do for that is refer to the calling object, and then call it's find method, but as I said, this gives me a bunch of errors.

Anyone help me out with how I can call this, thank you!

Upvotes: 2

Views: 6192

Answers (2)

iammilind
iammilind

Reputation: 69988

this is a pointer, if you want to use it it should be in either of the following ways:

this->find(x);
(*this).find(x);
find(x);

On side note, your function SLList<T>::add(const T& x) should return bool (not void).

Upvotes: 1

Pete
Pete

Reputation: 10871

Just call find(x). No this required. Also, this is a pointer to the current object. So you would have to do this->find(x).

Upvotes: 4

Related Questions