this-> not working

hi guys this is probably a very simple error

anyway I am having a problem with using this-> in my initialiser list

I checked on the forums to see if anybody else had this problem but no such luck

I can't see where I am going wrong



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 <iostream>
using namespace std;

class Test{

public:

	string name;
	int age;

	Test(int age,string name):

		this->name(name),this->age(age)
	{


	}

	Test(const Test& other){




	}


};


int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	return 0;
}
That's just not how you do it. You cannot use this-> in initialization lists.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

class Test{
public:
    string name;
    int age;
    Test(int age, string name):
        age(age), name(name) 
    {
    }

    Test(const Test& other){
    }
};

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}
Last edited on
that makes sense thanks Ihatov =)
Hello adam2016,

Ihatov has one approach, but I would offer this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Test
{

public:
	Test(int age, string name) : m_name(name), m_age(age) {}

	Test(const Test& other)	
	{
	}

private:
	string m_name;
	int m_age;
};


Putting "name" and "age" as "public" variables defeats the purpose of the class. If they are public variables you always have access to them. Also not a good idea to use a function parameter name with the same name a your class variables. Even if it works it is confusing and hard to follow.

Hope that helps,

Andy
very good point Andy =)

thanks
Topic archived. No new replies allowed.