C++ difference between class member variable access from member function

closed account (i8q9z8AR)
What's difference between member1, member2, member3 on CLS class ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  # include <stdio.h>

class CLS {
	char * name = (char *) "My name is Bikash.";
	public:
	void member1();
	void member2();
	void member3();
};


int main() {
	
	CLS x;
	x.member1();
	x.member2();
	x.member3();
	
	return 0;
}


void CLS::member1() {
	printf("%s\n", name);
}

void CLS::member2() {
	printf("%s\n", CLS::name);
}

void CLS::member3() {
	printf("%s\n", this->name);
}


Output :

My name is Bikash.
My name is Bikash.
My name is Bikash.
Last edited on
What's difference between member1, member2, member3 on CLS class ?
Semantically, there's no difference in this case.

The additional qualifiers are sometimes needed to disambiguate names, when the name is shadowed, or when looking up a non-dependent name inherited from a dependent base-class.

For completeness, you could also add a fourth case:
1
2
3
void CLS::member4() { 
  printf("%s\n", this->CLS::name);
}

which is always redundant, as far as I know. (don't bet on it.)

If you conform to the practice of fully-qualifying names, it is a good idea to use this->, instead of writing the name of the class (which might change) again and again.
And, in turn, there are several different ways to access member functions as well:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# include <iostream>
# include <functional>
# include <string>

class CLS
{
    std::string name =  "My name is Bikash.";
	public:
	void member1()const;
	void member2()const;
	void member3()const;
};

int main() {

	CLS x{};

    using namespace std::placeholders;
	std::bind(&CLS::member1, _1)(x);

	std::mem_fn(&CLS::member2)(x);

	auto l = [&x](){x.member3();}; //lambda
    l();
}


void CLS::member1()const {
	std::cout << name << "\n";
}

void CLS::member2()const {
	std::cout << CLS::name << "\n";
}

void CLS::member3()const {
	std::cout << this->name << "\n";
}
Topic archived. No new replies allowed.