I would be really appreciated if you can clarify for me the following issue:
Why the ways of initialization in the bellow code work? and they give the same result?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
class ex{
private:
float x,y;
public:
ex():x(0),y(0){}
ex(float m,float n):x(m),y(n){};
ex(float m):x(m),y(0){};
void show(){
cout<<"{"<<x<<","<<y<<"}"<<endl;
}
};
int main(){
ex x0=(2,3);
ex x1=3;
x0.show();
x1.show();
}
When you write ex x0=(2,3); (2, 3) evaluates to 3 before calling the constructor so both x0 and x1 are calling the single argument constructor with the value 3.
Maybe you you will get the expected result by removing the = from x0
Thank krako. Can you give me the principle why they work. I mean for initialization we use constructors like ex x0(2,3) or x0(3). I do not understand the reason why assignment works here.
I do not understand the reason why assignment works here.
The equal sign makes line 15 an assignment statement, not a constructor.
The line 15 parse is:
1 2
x1 = <expression>
Where <expression> is (2,3)
The parentheses are effectively ignored.
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.
Actually, I still don't understand why an assignment can invoke a constructor of a class here.
Or can I understand roughly like that:
For an integer variable, there are two way to initialize its value, they are:
1 2
int intvar=2;
int intvar(2);
For an object of a class, the principle is similar. And only one-argument constructor is invoked in this case?
Another issue: why in the following case, the assignment can initialize 3 properties of an object:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
usingnamespace std;
class s{
public:
int x,y,z;
};
int main(){
s t1={1,2,3};
cout<<t1.x<<","<<t1.y<<","<<t1.z<<endl;
}
However, if I add constructors for the above class like that:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
class s{
public:
int x,y,z;
s():x(0),y(0),z(0){};
s(int x1):x(x1),y(0),z(0){};
};
int main(){
s t1={1,2,3};
cout<<t1.x<<","<<t1.y<<","<<t1.z<<endl;
}
, the compiler throws errors like that:
1 2 3 4
C0_4.cc:10:13: error: in C++98 ‘t1’ must be initialized by constructor, not by ‘{...}’
s t1={1,2,3};
^
C0_4.cc:10:13: error: could not convert ‘{1, 2, 3}’ from ‘<brace-enclosed initializer list>’ to ‘s’