What does this mean: "member reference type 'Human *' is a pointer; did you mean to use '->'?"

Viewed 4907

I am working on classes in C++.

I am basically remaking what I was doing here, but in C++.

It has gone pretty well, but I don't understand what the error member reference type 'Human *' is a pointer; did you mean to use '->'? means. I've never used -> and I've seen * be used in that way (like const char *) but I'm not too sure how it works.

The closest question that I found was this one, but the replies weren't of help.

Here is my code

#include <stdio.h>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::cin;
using std::string;

class Human {
    public:
    string Name;
    int Age;
    double Height;

    void Initialise(string name, int age, double height) {
        this.Name = name; // Error here
        this.Age = age; // Error here
        this.Height = height; // Error here
    }

    void Grow(double rate) {
        if (rate < 0) {
            cout << "You can't grow at a negative rate, silly.\n";
            return;
        }
        else if (rate >= 0.2) {
            cout << "You can't grow that high, silly.\n";
            return;
        }
        this.Height += rate; // Here too
    }
};

int main() {
    return 0;
}
1 Answers
  1. this is always a pointer, so you cannot saythis.Name—you would need to say (*this).Name instead.

  2. The syntax a->b is equivalent to (*a).b so you could say this->Name (which is what the error message is explicitly suggesting), although:

  3. Inside methods, this-> is redundant. Usually you can simply refer to, or assign to, Name (although, as Jeremy Friesner points out in his comment, there may be rare/esoteric cases where you might actually want or need it).

  4. As the comments say, C++ must be learned formally. You simply have to know points 1 & 2 (and a million other conventions like them). You can't stumble upon them. Trial and error will not work.

  5. The -> syntax is not even C++ specific. It is part of C. The C rulebook is very slim—so it would be a good idea to formally learn that first before moving on to (and here I can only concur with user4581301) the "batsmurf crazy" complexity of C++.

Related