Consider I have this piece of code:

#include <iostream>

using namespace std;


class grid
        TEXTURE type;
        string str;

grid layer[5];

int main()
    layer[0].str = "AAAAA";
    layer[1].str = "A A A";
    layer[2].str = " A A ";
    layer[3].str = "  A  ";
    layer[4].str = "AA AA";

    grid *ptr;
    ptr = &layer[0];

    if(* == 'A')
        cout << "TRUE!\n";

When I attempt to compile, it give me this error:
error: request for member str in ptr, which is of non-class type grid*
*I want to fix this so I can access the member variable str through ptr.
How do I fix it?

Re: Accessing a member variable from a pointer to a class object 80 80

The dot operator and member function call have priority over the dereference operator. This means that the expression * is evaluated as *(, and that is why you get the error "str" is not a member of the pointer type grid*.

To fix it, you just need parentheses, like so: (*ptr) Or, C++ provides a shorter syntax for this very common operation, which is as follows: ptr->, where the arrow p-> basically replaces the (*p)..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.