Variable Name Ambiguity in Class Member Function

In C++, class member functions deal with primarily two types of variables – member variables and input variables. We don’t need to take special care in accessing them. C++ has a requirement that all member variables will have unique names. Similarly, all input variables will have unique names also. But an input variable of a member function can have the same of a member variable. In this situation the member function will have a trouble in accessing them separately.

class c1 {
public:
    int x;

    void func(int x) {

    }
};

This c1 class has a member variable, x. The member function, func(), has two variables – the member variable and the input variable. Both have the same name, x.

Let see what happens if we access the variable with the name, x.

#include <iostream>
using namespace std;

class c1 {
public:
    int x;

    void func(int x) {
        cout << x << endl;
    }
};

int main() {
    c1 obj;
    obj.x = 10;

    obj.func(20);

    return 0;
}

We printed the variable, x, from the func() function. In the main(), we first created an object from the class. Then set the member variable with 10. After that, the member function is called with 20. So, the member function has two variables. The member variable, x, with value 10 and the input variable, x, with value 20.

Let see what the ‘cout’ statement prints.

$ g++ -o test test.cpp 
$ ./test 
20

So, the value of the input variable is printed.

Now, how can we access the member variable then? We can access that using the special this pointer.

#include <iostream>
using namespace std;

class c1 {
public:
    int x;

    void func(int x) {
        cout << this->x << endl;
    }
};

int main() {
    c1 obj;
    obj.x = 10;

    obj.func(20);

    return 0;
}
$ ./test 
10

In fact, we can access both the variables together.

#include <iostream>
using namespace std;

class c1 {
public:
    int x;

    void func(int x) {
        cout << "Member variable: " << this->x << endl;
        cout << "Input variable: " << x << endl;
    }
};

int main() {
    c1 obj;
    obj.x = 10;

    obj.func(20);

    return 0;
}
$ ./test 
Member variable: 10
Input variable: 20

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0