Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function on the this keyword

Tags:

c++

function

this

So in my header file I have these two variables declared as private

private:

    char* data;

    int len;

and give this to access it

int length() const { return len; }

Then in my cpp file I am trying to override the operators in string implementation like this:

bool MyString::operator>(const MyString& string)
 {
    //Compare the lengths of each string
    if((this.length()) > (string.length())){
        return 0;
    }
    //The given string is shorter
    return -1;
 }

when I compile this I get this error:

mystring.cpp:263:14: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’

From what I can tell by trying to call the .length() on the this is trying to access a variable on the this pointer which is causing a problem, like in this question.

That's fine because I can do this instead:

 bool MyString::operator>(const MyString& string)
 {
    //Compare the lengths of each string
    if((this->len) > (string.length())){
        return 0;
    }
    //The given string is shorter
    return -1;
 }

which compiles fine but now I'm wondering how do you call a function on a this pointer. I thought that because it was a pointer I would have to dereference it first so I tried this:

bool MyString::operator>=(const MyString& string)
 {
     //Compare the lengths of each string
     if((*(this).length()) >= (string.length())){
         return 0;
     }
     //The given string is shorter but not equal
     return -1;
 }

But again I got this error:

mystring.cpp:273:17: error: request for member ‘length’ in ‘this’, which is of non-class type ‘MyString* const’

It seems like this should have worked fine as I would have dereferenced the pointer into the object it pointed to which does indeed have that method but I seem to be missing something. How would I go about calling a function defined in my class on the this pointer? And is there some functional reason why the way I described above does not work?

like image 256
user3282276 Avatar asked Nov 23 '14 09:11

user3282276


1 Answers

if((this.length()) > (string.length())){

This should be

if((this->length()) > (string.length())){

as this is a pointer.Basically this is just a pointer referring to the object on which member function is called. So, you have to use -> for all reference to members of that class.

One more advice stop using variable names which are standard keywords. like string in your case. Had you included std namespace you would have got the reason for not doing so.

like image 54
ravi Avatar answered Sep 21 '22 15:09

ravi