tags:

views:

485

answers:

4

E,g

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

  private:

      string isVal;
};
+29  A: 

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

Chris Jester-Young
+15  A: 

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.

FryGuy
Why was this down-voted? It's perfectly legal... (Ignoring possible operator overloads.)
strager
I'm voting this back up. It's not the way I'd do it but it is legal, and therefore helpful. What happens if your keyboard ">" key is broken and you're on a tight deadline? :-).
paxdiablo
...use trigraphs? :-P :-P :-P
Chris Jester-Young
(Clearly a facetious comment, because there is no trigraph or digraph that makes the <> characters---but there are ones that _use_ those characters! :-P)
Chris Jester-Young
Wow, I didn't think it'd be that controversial. I was just trying to use the non-syntactic-sugar version to illustrate that "this" is a pointer.
FryGuy
what about <:0:> hehe.
Johannes Schaub - litb
anyway, this guys answer works irrespective of any operator overloads. so it's rly 100% equivalent always.
Johannes Schaub - litb
You could even do: Test that.isVal = str;
Ates Goral
Well I think this kind of answer with out explanation especially for someone who is obviously a beginner isn't that great of an answer. That could just be me though.
Adam Peck
Whoa. Is this actually legal? Is it part of the C++ spec that (*this).isVal is functionally different from (Test b=*this; b.isVal)? Because it seems like they should both return a *new* instance similar to the original, but the former actually affects `this`.
Chuck
@Chuck: Read Ates's comment more carefully. They said: "Test that.isVal = str;" meaning that "that" is a _reference_ to (not a new copy of) this.
Chris Jester-Young
Johannes Schaub - litb
I found it helpful, although the answer should probably say "But you wouldn't do this."
too much php
+8  A: 

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

isVal = str;
sth
personally, I favor explicitly using this, as it allows you to shadow parameter names (which prevents stupid dummy names) and it works with templates and dependent bases.
coppro
A: 

For design scope you can use so :

Test::isVal = str;

lsalamon