dot (.) operator in C++
Last Updated :
19 Oct, 2023
The C++ dot (.) operator is used for direct member selection via the name of variables of type class, struct, and union. It is also known as the direct member access operator. It is a binary operator that helps us to extract the value of the function associated with a particular object, structure, or union.
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.
Example:
C++
#include <iostream>
using namespace std;
class base {
public :
int var1;
base( int x) { var1 = x; }
void getValue()
{
cout << "Member Function Called" << endl;
}
};
int main()
{
base b(222);
b.getValue();
cout << "Member Variable Value: " << b.var1;
return 0;
}
|
Output
Member Function Called
Member Variable Value: 222
Frequently Asked Questions about dot (.) Operators in C++
Is dot (.) actually an Operator?
Yes, dot (.) is actually an operator in C/C++ which is used for direct member selection via object name. It has the highest precedence in Operator Precedence and Associativity Chart after the Brackets.
Is there any other Operator like the dot(.) operator?
Yes. There is another such operator (->). It is called an “Indirect member selection” operator and its precedence is same as that of the dot (.) operator. It is used to access the members indirectly with the help of pointers. To know more about arrow(->) operator refer to this article.
Example:
C++
void addXtoList(Node* node, int x)
{
while (node != NULL) {
node->data = node->data + x;
node = node->next;
}
}
|
Can the dot (.) operator be overloaded?
No, the dot (.) operator cannot be overloaded in C++. Doing so will cause an error.
Example:
C++
#include <iostream>;
using namespace std;
class cantover {
public :
void fun();
};
class X {
cantover* p;
cantover& operator.() { return *p; }
void fun();
};
void g(X& x)
{
x.fun();
}
|
Output:
prog.cpp:11:20: error: expected type-specifier before '.' token
cantover& operator.()
^
prog.cpp:11:12: error: expected ';' at end of member declaration
cantover& operator.()
^
prog.cpp:11:20: error: expected unqualified-id before '.' token
cantover& operator.()
^
prog.cpp: In function 'void g(X&)':
prog.cpp:15:7: error: 'void X::fun()' is private
void fun();
^
prog.cpp:19:8: error: within this context
x.fun(); // X::fun or cantover::fun or error?
^
Share your thoughts in the comments
Please Login to comment...