Arrow Operator as Class Member Access Operator in C++

Learn: How to use Arrow Operator instead of Class Member Access Operator in C++ programming language, how to access members of a class through object pointer in C++?

Previously, we have discussed about Class Member Access Operator in C++ , which is used to access public members of a class.

To access public members of a class, we use object_name.member_name.

Accessing Class Members with Pointer to an Object

If you have a pointer to an object and want to access the class members, you can access them by using combination of two operators Asterisk (*) and Dot (.) operator.

Syntax:

(*object_pointer_name).member_name;

Consider the given class declaration

class sample
{
	private:
		int a;
	public:
		int b;
		void init(int a)
		{this->a = a;}
		void display()
		{cout<<"a: "<<a<<endl;}
};

Consider the main(), here we are accessing the member function by using combination of * and . Operators:

int main()
{
	//pointer to an object declaration
	sample *sam = new sample();
	
	//value assignment to a and back
	(*sam).init(100);
	(*sam).b=200;
	
	//printing the values
	(*sam).display();
	cout<<"b: "<<(*sam).b<<endl;
	
	return 0;
}

Arrow Operator (->) instead Asterisk (*) and Dot (.) Operator

We can use Arrow Operator (->) to access class members instead of using combination of two operators Asterisk (*) and Dot (.) operator, Arrow operator in also known as “Class Member Access Operator” in C++ programming language.

Syntax:

object_pointer_name -> member_name;

Consider the main(), here we are accessing the members using Arrow Operator

int main()
{
	//pointer to an object declaration
	sample *sam = new sample();
	
	//value assignment to a and back
	sam->init(100);
	sam->b=200;
	
	//printing the values
	sam->display();
	cout<<"b: "<<sam->b<<endl;	
	
	return 0;			
}

Here is the complete program

#include <iostream>
using namespace std;

class sample
{
	private:
		int a;
	public:
		int b;
		void init(int a)
		{this->a = a;}
		void display()
		{cout<<"a: "<<a<<endl;}
};

int main()
{
	//pointer to an object declaration
	sample *sam = new sample();
	
	cout<<"Using * and . Operators\n";
	//value assignment to a and back
	(*sam).init(100);
	(*sam).b=200;
	
	//printing the values
	(*sam).display();
	cout<<"b: "<<(*sam).b<<endl;
	
	cout<<"Using Arrow Operator (->)\n";
	//value assignment to a and back
	sam->init(100);
	sam->b=200;
	
	//printing the values
	sam->display();
	cout<<"b: "<<sam->b<<endl;	
	
	return 0;			
}

Output

Using * and . Operators 
a: 100
b: 200
Using Arrow Operator (->) 
a: 100
b: 200 

Related Tutorials




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.