Quick links: C-Tricks HR Interview Que. Code Snippets C Programs C++ Programs Java Programs PHP Examples

Home » C++ programming language

Class Member Access Operator in C++ programming language

Learn: What is Class Member Access Operator in C++ programming language, how to access public members (data members/member functions) in C++ using object?

Dot (.) operator is known as "Class Member Access Operator" in C++ programming language, it is used to access public members of a class. Public members contain data members (variables) and member functions (class methods) of a class.

Syntax:

object_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;}
};

In this class declaration, following are the class members that can be accessed through the "Class Member Access Operator":

Public data member: b

Public member functions: init(), display()

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()
{
	//object declaration
	sample sam;
	//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

a: 100
b: 200

Consider the following statements in main() function

sam.init(100); - This statement will assign 100 to the private data member a through this public member function.
sam.b=200; - This statement will assign 200 to the public data member b.





Sponsored Links




COMMENTS