Q:

Accessing Member Function by pointer in C++

belongs to collection: C++ Classes and Object programs

0

How to access a member function by pointer?

To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this).

The second step, use arrow operator -> to access the member function using the pointer to the object.

Syntax:

//pointer to object declaration
class_name *pointe_name;
//memory initialization at runtime 
pointer_name = new class_name;
//accessing member function by using arrow operator
pointer_name->member_function();

Example:

In the below example - there is a class named Number with private data member num and public member functions inputNumber()displayNumber().

In the example, we are creating simple object N and a pointer to the object ptrN and accessing the member functions by using simple object N and the pointer to the object ptrN.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#include <iostream>
using namespace std;

class Number
{
	private:
		int num;
	public:
		//constructor
		Number(){ num=0; };
		
		//member function to get input
		void inputNumber (void)
		{
			cout<<"Enter an integer number: ";
			cin>>num;
		}
		//member function to display number 
		void displayNumber()
		{
			cout<<"Num: "<<num<<endl;
		}
};

//Main function
int main()
{
	//declaring object to the class number
	Number N;
	//input and display number using norn object
	N.inputNumber();
	N.displayNumber();

	//declaring pointer to the object 
	Number *ptrN;
	ptrN = new Number; //creating & assigning memory 
	
	//printing default value
	cout<<"Default value... "<<endl;
	//calling member function with pointer 
	ptrN->displayNumber();
	
	//input values and print 
	ptrN->inputNumber();
	ptrN->displayNumber();

	return 0;
}

Output

Enter an integer number: 10
Num: 10
Default value...
Num: 0
Enter an integer number: 20
Num: 20

Explanation:

The main three steps needs to be understood those are:

 
  1. Pointer to object creation: Number *ptrN;
  2. Dynamic memory initialization to the pointer object: ptrN = new Number;
  3. Accessing member function by using "Arrow Operator"ptrN->displayNumber();

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Classes and Object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Access the address of an object using \'this\... >>
<< Passing an object to a Non-Member function in C++...