Q:

Accessing Member Function by pointer in C++

belongs to collection: C++ programs on various topics

0

Accessing Member Function by pointer in C++

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++ programs on various topics

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\... >>
<< Set values of data members using default, paramete...