jcodebook

Pointer to Members in C++: An Introduction

Pointers to members in C++ are a concept that allows you to store and manipulate pointers to class or struct members. Unlike regular pointers, which point to data or functions, pointers to members point to specific members (variables or functions) within a class or struct.

They are a powerful feature in C++ that enables you to work with class members in a dynamic and flexible way.

In this post, you will learn

  • Pointer to Members
  • Pointer to Member Function
  • Example-1: Pointer to Data Member
  • Example-2: Pointer to Member Function
  • Pointer to Object
  • Example – Pointer to Object

Pointer to Members

Pointer to members in C++ allows you to store and manipulate pointers to class or struct members.

We can assign the address(using the &) of a class member (variables or functions) and assign it to a pointer variable.

It is a powerful feature in C++ that enables you to work with class members in a dynamic and flexible way.

A class member pointer can be declared using the operator ::* with the class name.

For example, given a class MyClass

class MyClass{
    private:
        int data;
    public:
        void show();
};

We can define the pointer to a member e.g. data using operator ::* as follows

int MyClass ::* ptr=&MyClass :: data;

Here, the statement MyClass ::* ptr is “pointer-to-member” of the class MyClass.

The statement &MyClass :: data means the address of the member i.e. data of MyClass.

Important Note!

int *ptr=&data; //It is not valid

Now, the pointer *ptr can be used to access the member data inside member function or friend function.

Let’s say obj is an object of MyClass, we can access the data using the pointer ptr as follows.

cout<<obj.*ptr; 
cout<<obj.data; //It is same as above

Example 1: Pointer to Data Member

//PointerToMemberEx1.cpp
#include <iostream>
using namespace std;

class MyClass {
public:
    int myData;
    MyClass(int data) : myData(data) {}
};

int main() {
    MyClass obj(10);
    int MyClass::*ptr = &MyClass::myData; // Define a pointer to a data member

    // Access the data member using the pointer
    int value = obj.*ptr;

    cout << "Value of myData: " << value <<endl;
    return 0;
}

Output

Value of myData: 10

Pointer to Member Function

A pointer to a member function in C++ is a pointer that can store the address of a member function of a class or struct

Syntax

// Define a pointer to a member function
return-type (class-name ::*pointer-to-member function)(arg list)
= &Class-name::member-function-name

//Call the member function
object-name.*pointer-to-member-function(arg list);

Example

/* Define a pointer to a member function.
Let's say, A is a class, add is a method */
int (A::*addPtr)(int,int)=&A::add;

//Call the member function
cout<< obj.*addPtr(5,6); //obj is the object of class A

Example 2: Pointer to Member Function

//PointerToMemberEx2.cpp
#include <iostream>
using namespace std;

class MathOperations {
public:
    int add(int a, int b) {
        return a + b;
    }
    int subtract(int a, int b) {
        return a - b;
    }
};

int main() {
    MathOperations math;
    // Define a pointer to a member function
    int (MathOperations::*addPtr)(int, int) = &MathOperations::add; 
    
    // Call the member function using the pointer
    int result = (math.*addPtr)(5, 3);

    cout << "Result of addition: " << result <<endl;
    return 0;
}

Output

Result of addition: 8

Pointer to Member Operators

S.N.OperatorMeaning
1.::Scope Resolution Operator
2.::*Pointer-to-Member Declarator
3.->*Pointer-to-Member. Used to access a member using a pointer to an object and a pointer to that member.
4..*Pointer-to-Member. Used to access a member using an object and a pointer to that member.

Pointer to an Object

A pointer to an object is a pointer that can store the memory address of an object.

Syntax

MyClass obj; //Creating an object obj

//objPtr is a Pointer to object obj
MyClass* objPtr = &obj; 

// Display data, *ptr is pointer to member 'data'
cout<< objPtr ->* ptr; //Where, int MyClass ::* ptr=&MyClass :: data;

cout<<objPtr ->data; //Same a above

The dereferencing operator ->* is used to access the member in case of pointers to both object and member.

Example

// Display data, *ptr is pointer to member 'data'
cout<<objPtr ->* ptr; 

The dereferencing operator .* is used when an object itself accesses the member pointer.

MyClass obj;
cout<<obj.*ptr; //Accessing Member pointer

Example 3: Pointer to Object

//PointerToObjectEx1.cpp
#include <iostream>
#include <string>
using namespace std;

class Car {
public:
    string make;
    string model;
    int year;

    Car(string make, string model, int year)
        : make(make), model(model), year(year) {}

    void startEngine() {
        cout << "Starting the engine of " << year 
        << " " << make << " " << model <<endl;
    }
};

int main() {
    // Creating an object of the Car class
    Car myCar("Toyota", "Camry", 2022);

    // Creating a pointer to a Car object
    Car* carPointer = &myCar;

    // Accessing object members using the pointer
    cout << "Car Make: " << carPointer->make <<endl;
    cout << "Car Model: " << carPointer->model <<endl;
    cout << "Car Year: " << carPointer->year <<endl;

    // Calling a member function through the pointer
    carPointer->startEngine();

    return 0;
}

Output

Car Make: Toyota
Car Model: Camry
Car Year: 2022
Starting the engine of 2022 Toyota Camry

Explanation

1. We create an instance of the Car class called myCar with specific values.

2. We create a pointer to a Car object named carPointer and initialize it with the memory address of the myCar object.

3. We use the arrow operator -> to access and display the make, model, and year members of the myCar object through the carPointer.

4. We call the startEngine member function of the myCar object through the carPointer.

Using pointers to objects allows you to perform operations on objects indirectly, making it useful in various scenarios, such as dynamic memory allocation, polymorphism, and managing collections of objects efficiently.

Example 4: Pointer to Object

//PointerToObjectEx2.cpp
#include <iostream>
using namespace std;

class Addition{
    int x,y;
    
    public:
    void setXY(int a, int b){
        x=a;
        y=b;
    }
    
    friend int add(Addition ob);
};

int add(Addition ob){
    int Addition::*xPtr=&Addition::x;
    int Addition::*yPtr=&Addition::y;

    Addition *obPtr=&ob;
    int sum=ob.*xPtr+obPtr->*yPtr;
    return sum;
}
int main(){
    Addition obj1;

    // Define a pointer to a member function
    void (Addition::*setPtr)(int,int)=&Addition::setXY;

    // Call the member function using the pointer
    (obj1.*setPtr)(5,10);
    cout<<"Addition: "<<add(obj1)<<endl;

    Addition *obj1Ptr=&obj1;
    (obj1Ptr->*setPtr)(25,35);
    cout<<"Addition: "<<add(obj1);

    return 0;
}

Output

Addition: 15
Addition: 60

Student Ratings and Reviews

There are no reviews yet. Be the first one to write one.

Submit a Review

    JCB Tutor
    👋 Hi! Ask me anything about this article.