Reputation: 61
using the scope resolution operator in the below code during the initialization in the constructor gives me error. Why can I only use scope resolution operator in front of the function name (i.e.Vector::Vector(int i)?
class Vector {
public:
Vector(int s); // declaration an interface to definition or what part is.
double& operator[] (int i);
int size();
private:
double* elem;
int sz;
};
Vector::Vector(int s) : Vector::elem{new double[s]},Vector::sz{s} { }
double& Vector::operator[] (int i) { return Vector::elem[i]; }
int Vector::size() { return Vector::sz; }
int main() {
int s = 10;
Vector V(10);
return 0;
}
Upvotes: 2
Views: 414
Reputation: 181
So, my try is the following, but before checking the code, i suggest you to take a look at Member Initializer Lists, a nice example is posted there :
class X {
int a, b, i, j;
public:
const int& r;
X(int i)
: r(a) // initializes X::r to refer to X::a
, b{i} // initializes X::b to the value of the parameter i
, i(i) // initializes X::i to the value of the parameter i
, j(this->i) // initializes X::j to the value of X::i
{ }
};
So your code can be like the following :
#include <iostream>
class Vector {
public:
Vector(int s); // declaration an interface to definition or what part is.
double& operator[] (int i);
int size();
private:
double* elem;
int sz;
};
Vector::Vector(int s) :sz{s} {
elem = new double[s];
}
double& Vector::operator[](int i) {
return elem[i];
}
int Vector::size() {
return sz;
}
int main() {
int s = 10;
Vector v{10};
return 0;
}
Upvotes: 0
Reputation: 17454
The member-initialisation list is more constrained than some arbitrary expression.
While it is true that you can qualify member names, like Vector::sz
, in expressions generally (where sz
is in scope), the syntax of a part of the member-initialisation list simply does not support this. You must write name(init)
or name{init}
; nothing else.
C++ could have been made to allow qualified names here, but there would have been absolutely no point in doing so, while making the parser more complex.
Fortunately, none of us actually needs to worry about this in any way whatsoever.
tl;dr: Because.
Upvotes: 2