c++ - Accessing a data member of a pointer -



c++ - Accessing a data member of a pointer -

class cat { public: int name; cat(); int getname(); }

if have a:

cat* pointer = new cat(); pointer->getname(); pointer->name; //this doesn't work

so how can access info member: name?

it works fine: http://ideone.com/3e5uec

#include <iostream> using std::cout; using std::endl; class cat { public: int name; cat() : name(0) { } int getname() { homecoming name; } }; int main() { cat* pointer = new cat(); pointer->name = 42; cout << "getname: " << pointer->getname() << endl; cout << "name: " << pointer->name << endl; delete pointer; }

note had create additions code provided, did not compile gave it:

i added missing #include directives i added definitions cat::cat() , cat::getname() i added missing ; after class definition i wrapped code in main(), , output result of pointer->name verify worked

c++

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -