It works just fine: http://ideone.com/3E5Uec
#include <iostream>
using std::cout; using std::endl;
class Cat
{
public:
int name;
Cat() : name(0) { }
int getName() { return name; }
};
int main()
{
Cat* pointer = new Cat();
pointer->name = 42;
cout << "getName: " << pointer->getName() << endl;
cout << "name: " << pointer->name << endl;
delete pointer;
}
Note that I had to make some additions to the code that you provided, as it did not compile as you gave it:
- I added missing #include directives
- I added the definitions for Cat::Cat() and Cat::getName()
- I added the missing
;
after the class definition - I wrapped your code in main(), and output the result of
pointer->name
to verify that it worked
solved Accessing a data member of a pointer [closed]