dot (.) operator in C++ is used to access members (data and functions) of a class, struct, or union through an object. It allows direct interaction with an object’s components.
- The dot (.) operator accesses member variables and functions using objects (not pointers) and is used for direct member access.
- It has very high precedence in C++, just below brackets, and shares the same level with the arrow (->) operator.
- The arrow (->) operator works similarly but accesses members through pointers instead of objects.
- The dot (.) operator cannot be overloaded, and attempting to do so causes compile-time errors.
#include <iostream>
using namespace std;
class Student {
public:
int roll;
void show() {
cout << "Roll number is: " << roll << endl;
}
};
int main() {
Student s;
s.roll = 10;
s.show();
return 0;
}
Output
Roll number is: 10
Syntax
variable_name.member;
- variable_name: It's an instance of a class, structure, or union.
- member: member variables or member functions associated with the created object, structure, or union.
#include <iostream>
using namespace std;
class Car {
public:
string model;
int year;
Car(string m, int y) {
model = m;
year = y;
}
void showDetails() {
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};
int main() {
Car c("BMW", 2024);
cout << "Accessing data members:" << endl;
cout << c.model << endl;
cout << c.year << endl;
cout << "Accessing member function:" << endl;
c.showDetails();
return 0;
}
Output
Accessing data members: BMW 2024 Accessing member function: Model: BMW Year: 2024