Reputation: 43
Why cant we use this
in initialization list like this?
It threw an error cant find {
before this
..
But scope is not the problem because the second code works
class Student {
public :
int age;
const int rollNumber;
int &x; // age reference variable
Student(int r, int age) : rollNumber(r), this->age(age), x(this -> age) {
//rollNumber = r;
}
"This" one works:
class Student {
public :
int age;
const int rollNumber;int &x;
Student(int r, int age) : rollNumber(r), x(this -> age) {
//rollNumber = r;
}
I know we have to declare and initialize const
and reference variables at same time but I want to initialize them after taking an input and passing to my objects
Upvotes: 0
Views: 67
Reputation: 25895
The short answer is "this is how it was decided the syntax would be", but from a philosophical standpoint, you might say that this->age
does not exist in the initializer list (since you did not construct this
yet...). Just:
age(age)
is the correct syntax, and it is clear from the context which age
is which here.
Upvotes: 5