kal
kal

Reputation: 29353

Why can't we use "this" inside the class?

E,g

class Test {
  public:
      void setVal(const std::string& str) {
           this.isVal = str; //This will error out
      }

  private:

      string isVal;
};

Upvotes: 2

Views: 630

Answers (4)

lsalamon
lsalamon

Reputation: 8174

For design scope you can use so :

Test::isVal = str;

Upvotes: 0

FryGuy
FryGuy

Reputation: 8744

Adding to Chris's answer, you can also do:

(*this).isVal = str;

However, it's better to do what Chris said, as it is more orthodox. This is just illustrating that you need to de-reference the pointer before calling methods on it.

Upvotes: 15

sth
sth

Reputation: 229583

You also don't really need to use this explicitly to access member variables/methods. You can simply say:

isVal = str;

Upvotes: 8

C. K. Young
C. K. Young

Reputation: 223003

In C++, this is a pointer (as opposed to a reference). So you have to say this->isVal instead.

Upvotes: 33

Related Questions