Dot Operator in C++
The dot operator (.
) is used to access the members of an object or struct when working directly with objects or references. It is applied to the actual object directly to access variables, functions, and other class members.
Syntax to Use Dot Operator
Object.member
Here,
- object is an instance of the class.
- member is the name of the variable or function of the object that we want to access.
Note: The dot operator can only be used with actual object instances, not pointers.
Example
The below example demonstrates how we can use dot operator to access members of an object in C++.
// C++ program to use dot operator in C++
#include <iostream>
using namespace std;
// define a class MyClass
class MyClass {
public:
int num;
void increase() { num += 5; }
};
int main()
{
// create object of MyClass
MyClass obj;
// access variable using dot operator
obj.num = 5;
// access member function using dot operator
obj.increase();
// printing the value of num
cout << "Number is: " << obj.num;
}
Output
Number is: 10
Arrow Operator vs. Dot Operator in C++
In C++, we use the arrow operator (->
) and the dot operator (.
) to access members of classes, structures, and unions. Although they sound similar but they are used in different contexts and have distinct behaviours. In this article, we will learn the key differences between the arrow operator and the dot operator in C++ and clarify the confusion.