Cpp - Accessing Data Members Using Pointers


Data members and functions are accessed by using the dot operator for objects created locally.

To access the Cat object via pointer, dereference the pointer and call the dot operator on the object pointed to by the pointer.

To access the GetAge member function, you write the following:


Parentheses are used to assure that my_pointer is dereferenced before GetAge() is accessed.

C++ provides a shorthand operator for indirect access: the points-to operator ->.

C++ treats this as a single symbol.


#include <iostream> 
class Employee //  ww  w .java 2 s  .  c  o  m
    Employee() { itsAge = 2; } 
    ~Employee() {} 
    int GetAge() const { return itsAge; } 
    void SetAge(int age) { itsAge = age; } 
    int itsAge; 
int main() 
    Employee *emp = new Employee; 
    std::cout << "emp is " << emp->GetAge() 
                   << " years old" << std::endl; 
    std::cout << "emp is " << emp->GetAge()  
                  << " years old" << std::endl; 
    delete emp; 
    return 0; 


Related Topic