Cpp - Accessing Data Members Using Pointers

Introduction

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:

(*my_pointer).GetAge(); 

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.

Demo

#include <iostream> 
 
class Employee /*from  w w  w .  ja va  2s.  c om*/
{ 
public: 
    Employee() { itsAge = 2; } 
    ~Employee() {} 
    int GetAge() const { return itsAge; } 
    void SetAge(int age) { itsAge = age; } 
private: 
    int itsAge; 
}; 
 
int main() 
{ 
    Employee *emp = new Employee; 
    std::cout << "emp is " << emp->GetAge() 
                   << " years old" << std::endl; 
 
    emp->SetAge(5); 
    std::cout << "emp is " << emp->GetAge()  
                  << " years old" << std::endl; 
 
    delete emp; 
    return 0; 
}

Result

Related Topic