0

Hi people,

I am making a little experiment to see something. I wished to inherit "string" class and add a function to child class.
Function should take a char as parameter and return bool depending on is there such a character in our string or not.

I have started off with this, but I got stuck with "this":

class MyStringClass:public string{
    public:
    MyStringClass(const char* a):string(a){};
    bool isInString(char);
};

bool MyStringClass::isInString(char s)
{
    for(int i=0;i<=this->length();++i){
        if(s==(*this)[i]) //here
            return true;

    }

    return false;

}

this has type of MyStringClass*?

If so, why can't we access to its elements this way: this[i]?

I assumed so since if we made a pointer like:

int* a=new int;
a[0]=3;

Why wouldn't it work with this too?

MyStringClass* this;
this[0]=something
3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by deceptikon
0

The issue here is that this is a pointer to the object as a whole, not just to an array; you would need to access the string's internal array to do this, and since that array is private, you cannot do that - at least not directly.

What you want to do is use the at() method to check the individual elements of the string:

bool MyStringClass::isInString(char s)
{
    for(int i=0;i<=this->length();++i){
        if(s == this->at(i)) 
            return true;
    }
    return false;
}

BTW, are you aware that there is already a method in the string class (find()) which does (more or less) what you are looking for? Just wondering.

0

Thank you for pointing out about at(int).
But still, I'm curious, why does (*this)[i] work?

P.S. I know about find(), but I was curious hehe

0

But still, I'm curious, why does (*this)[i] work?

Because you're dereferencing the this pointer and then accessing the overloaded [] operator (which is technically a member function). While it may look the same as a[i] in your example, under the hood the two are very different.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.