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

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.

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.