0

Possible Duplicate:
C++ equivalent to Java this

What is the c++ version of java's this. :

class javaObj{

private String name;

public void setName(String name)
{
    this.name = name;
}
}

Only thing i have found that works in c++ is:

class cppObj
{
private:
    string name;

public:
    void setName(string name);
};

void cppObj::setName(string name)
{
    cppObj::name = name;
}

must I use cppObj:: or is there a this. equivalent for c++?

Community
  • 1
  • 1
user1952452
  • 9
  • 1
  • 1
  • I don't know why you'd want to name the parameter the same, but `this` is a pointer, so it needs pointer syntax. – chris Jan 06 '13 at 07:40
  • Note that, as in Java, `this` is optional as long as the field being referenced can be unambiguously resolved (for example, a parameter or local is not defined with the same name). – cdhowie Jan 06 '13 at 07:42
  • Removing [tag:java] as the answer will not have anything to do with Java. – Peter Lawrey Jan 06 '13 at 09:56

4 Answers4

5

C++ equivalent of Java's this is as below:

this->name = name;

This post suggests an alternative syntax:

(*this).name = name;
Community
  • 1
  • 1
user1055604
  • 1,624
  • 11
  • 28
2

The C++ equivalent is the this pointer.

this->name = name;

It is more usual for this kind of operation to do the following:

void cppObj::setName(const string& name)
{
    name_ = name;
}

Where member variables are suffixed with an underscore and arguments are passed in by const reference (not copying the value of the string). There is no ambiguity here and the this pointer is not required.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

Yes, C++ has equivalent this pointer. the equivalent code is:

void cppObj::setName(string name)
{
    this->name = name;
}

However you could enhance your code:

class cppObj
{
private:
    std::string name_;   // better naming style to distinguish class member with other variables

public:
    void setName(const std::string& name);  // pass by reference to elide the unnecessary copy
};

void cppObj::setName(const std::string& name)
{
    name_ = name;  // not necessary to have to use `this->` pointer syntax
}
billz
  • 44,644
  • 9
  • 83
  • 100
0

like java, this, but "->" instead of ".";

ggrandes
  • 2,067
  • 22
  • 16