P
PengYu.UT
Hi,
I have the following code. I don't understand why "a" and "b" has the
same content, even their initialization codes are different.
My first conjecture was that
"a.show()" gave me "2 4"
but
"b.show()" gave me "2 0",
because in b when _y is initialized _x is still 0 if the initialization
is done from left to right.
Best wishes,
Peng
#include <iostream>
class A{
public:
A(int x) : _x(x),_y(_x * _x){}
void show(){
std::cout << _x << " " << _y << std::endl;
}
private:
int _x;
int _y;
};
class B{
public:
B(int x) : _y(_x * _x),_x(x){}
void show(){
std::cout << _x << " " << _y << std::endl;
}
private:
int _x;
int _y;
};
int main(int argc, char *argv[]) {
A a(2);
a.show();
B b(2);
b.show();
//a and b shows the same thing.
}
I have the following code. I don't understand why "a" and "b" has the
same content, even their initialization codes are different.
My first conjecture was that
"a.show()" gave me "2 4"
but
"b.show()" gave me "2 0",
because in b when _y is initialized _x is still 0 if the initialization
is done from left to right.
Best wishes,
Peng
#include <iostream>
class A{
public:
A(int x) : _x(x),_y(_x * _x){}
void show(){
std::cout << _x << " " << _y << std::endl;
}
private:
int _x;
int _y;
};
class B{
public:
B(int x) : _y(_x * _x),_x(x){}
void show(){
std::cout << _x << " " << _y << std::endl;
}
private:
int _x;
int _y;
};
int main(int argc, char *argv[]) {
A a(2);
a.show();
B b(2);
b.show();
//a and b shows the same thing.
}