this-> not working
Oct 16, 2017 at 7:25pm UTC
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;
}
Oct 16, 2017 at 7:37pm UTC
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 Oct 16, 2017 at 11:10pm UTC
Oct 16, 2017 at 8:19pm UTC
that makes sense thanks Ihatov =)
Oct 16, 2017 at 8:33pm UTC
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
Oct 17, 2017 at 12:53pm UTC
very good point Andy =)
thanks
Topic archived. No new replies allowed.