Skip to content
Related Articles

Related Articles

Improve Article

dot (.) operator in C/C++

  • Last Updated : 26 Nov, 2019

The dot (.) operator is used for direct member selection via object name. In other words, it is used to access the child object.

Syntax:

object.member;

For example:




#include <stdio.h>
  
struct Point {
    int x, y;
};
  
int main()
{
    struct Point p1 = { 0, 1 };
  
    // Accessing members of point p1
    // using the dot operator
    p1.x = 20;
  
    printf("x = %d, y = %d", p1.x, p1.y);
  
    return 0;
}
Output:
x = 20, y = 1

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 dot(.) operator?

Yes. There is another such operator (->). It is called as “Indirect member selection” operator and it has precedence just lower to dot (.) operator. It is used to access the members indirectly with the help of pointers.

Example:




void addXtoList(struct Node* node, int x)
{
    while (node != NULL) {
        node->data = node->data + x;
        node = node->next;
    }
}

Can dot (.) operator be overloaded?

No, Dot (.) operator can’t be overloaded. Doing so will cause an error.

Example:




// C++ program to illustrate
// Overloading this .(dot) operator
  
#include <iostream>
using namespace std;
  
class cantover {
public:
    void fun();
};
  
// assume that you can overload . operator
// Class X below overloads the . operator
class X {
  
    cantover* p;
  
    // Overloading the . operator
    cantover& operator.()
    {
        return *p;
    }
  
    void fun();
};
  
void g(X& x)
{
  
    // Now trying to access the fun() method
    // using the . operator
    // But this will throw an error
    // as we have overloaded the . operator above
    // Hence compiler won't allow doing so
    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? 
        ^
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :