Seatless
Seatless

Reputation: 193

accessing class field in c++

I can't have an access to the class'es field in the following C++ code:

class Human
{
     string address;
 public:
     void setAddress( string address )
     {
         this.address = address;
     }
};

This code will result into an error "error C2228: left of '.address' must have class/struct/union". What's the correct way of doing it?

Upvotes: 1

Views: 5516

Answers (2)

QuentinUK
QuentinUK

Reputation: 3077

  class Human
{
     string m_address;
 public:
     void setAddress( string address )
     {
         m_address = address;
     }
};

Unlike JavaScript you don't need to use "this". Here it would be usual to give the function parameter a different name to avoid ambiguity

Upvotes: 3

Coert Metz
Coert Metz

Reputation: 892

this is a pointer to your current instance, so you should use -> instead of a dot.

Upvotes: 7

Related Questions