Write a C++ program to call member functions of class in the main function using pointer to object and pointer to member function.

In this blog post, we will explore the concept of pointers to objects and pointers to member functions and provide a C++ program that demonstrates their usage.

Pointer to Object and Pointer to Member Function

Understanding Pointers to Objects

A pointer to an object that holds the memory address of an instance of a class. It allows us to access and manipulate the member variables and member functions of the object indirectly. To access the members of the object through the pointer, we use the arrow operator (->).

Understanding Pointers to Member Functions

Pointers to member functions are pointers that hold the addresses of member functions within a class. They are used to invoke specific member functions of an object dynamically. This can be especially useful when you need to select and execute different member functions at runtime.

Tutorial 📺

Code 💻

#include <iostream.h>
#include <conio.h>

class Number
{
  int num;
  public:
  void get()
  {
    cout << "Please enter the number: ";
    cin >> num;
  }
  void display()
  {
    cout << "Num: " << num;
  }
}; // class Number ends here

void main()
{
  clrscr();
  Number n; // object of class Number
  Number *ptr = &n; // pointer to object 'n'
  ptr->get(); // -> operator is used to call member function
  ptr->display();
  getch();
}

In the above code, we have a Number class with two member functions, get and display. In the main function, we create an instance of the Number class and a pointer ptr that points to this object. We then use the arrow operator (->) to call the member functions through the pointer, allowing us to interact with the object’s members (data and behaviour).


Categorized in:

Tagged in: