CPP Accessing Class Members
Accessing Class Members on object created on the free store.
-
To access the getAge member function of an object
pointed to by pPerson, you could write:
// parentheses are used to ensure that pPerson is dereferenced first (*pPerson).getAge();
-
Because this is cumbersome, C++ provides a shorthand
operator for indirect access: the class member access operator (->),
which is created by typing the dash (-) immediately followed by
the greater-than symbol (>).
Here is an Example
#include <iostream> using namespace std; class Person { public: int getAge() {return age;} void setAge( int Age) {age=Age;} private: int age; }; int main() { Person * pPers = new Person; // (*pPers).setAge(45); // Instead use: pPers->setAge(34); cout << "The person age is " << pPers->getAge() << endl; delete pPers; pPers=0; return 0; }
When we run this application the result will be:The person age is 34
You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data.
All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the
correctness in the pages or source codes.
The risk of using this web-site pages or any program
codes from this website is entirely at the individual user.