A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/dot-operator-in-cpp/ below:

dot (.) operator in C++

dot (.) operator in C++

Last Updated : 11 Jul, 2025

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;

Example:

C++
// C++ Program to demonstrate the use of dot operator
#include <iostream>
using namespace std;

class base {
public:
    int var1;

    base(int x) { var1 = x; }

    void getValue()
    {
        cout << "Member Function Called" << endl;
    }
};

// driver code
int main()
{
    // creating new object
    base b(222);
    // calling member function using dot(.) operator
    b.getValue();
    // getting member variable
    cout << "Member Variable Value: " << b.var1;
    return 0;
}

Output
Member Function Called
Member Variable Value: 222
C++
// C++ Function
// tO demonstrate
// Indirect member selection operator
void addXtoList(Node* node, int x)
{
    // Node is a class

    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++
// C++ program
// illustrate Overloading
// .(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?
^


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4