0

I have a struct that I never explicitly defined as a pointer. But when I try to access its member variables with a . instead of ->, I get an error, and -> seems to be the only correct option.

As far as I understand, you only use -> to dereference a pointer to a class and access its members. In the code below, Employee is not a pointer, but if I use ., I get an error. Why is that so?

struct Employee {
  public:
    int getAge(){ return this.age; }
    void setAge(int age){ this.age = age; }
  private:
    int age{18};
};

int main() {
  Employee emp;
  emp.setAge(55);
  std::cout << emp.getAge() << '\n';
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98

2 Answers2

3

In C++, this is a pointer to the current object rather than a reference to it. As a result, even though you’ve never declared any pointers, if you use this you’ll need to use pointer syntax.

(The reason this is a pointer and not a reference is historical. The this keyword was added to the language before references were.)

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
2

The reason why you have to use the -> operator is because this is a pointer. It is a special kind of pointer. The this pointer is a pointer that points to an object of which the member function was called. This is used to retrieve an object. The this pointer in your example is retrieving the object age. The this pointer is also an r-value. Specifically a prvalue. Here's the reference as well. Thanks to @user4581301 for contributing to this as well.

For example using your example and tweaking a few things:

#include <iostream>

struct Employee {
public:
 // You want to use pointer syntax for the this pointer. By using the arrow operator.
    int getAge() { return this->age; }
    void setAge(int age) { this->age = age; } //Then changing setAge to an int rather than a string.
private:
    int age{ 18 };
}; // Don't forget the semicolon. 

int main() {
    Employee emp;
    emp.setAge(55);
    std::cout << emp.getAge() << '\n';
}
Geno C
  • 1,401
  • 3
  • 11
  • 26