D
de
Hi,
Recently I came across these codes. I'm trying to figure out why it's
outputing its result in such a way...
The complete codes are:
#include <iostream>
struct Data {
Data(int i_ = 0) : _i(i_)
{
std::cout << "Data: " << _i << std::endl;
}
int _i;
};
struct Info {
Info(Data* d_) {
std::cout << "Info: " << d_->_i << std::endl;
d_->_i = 1;
}
};
struct Base {
Base(const Data& data_) {
std::cout << "Base: " << data_._i << std::endl;
}
};
struct Derived : Base {
Derived(int i_)
:_info(&_data), Base(_data = i_) {
std::cout << "Derived: " << _data._i << std::endl;
}
Data _data;
Info _info;
};
int main()
{
Derived d(100);
}
and if copy and run it, the outputs are:
Data: 100
Base: 100
Data: 0
Info: 0
Derived: 1
I'm expecting the constructor of Base is invoked first since it's base
class. Then the constructor of Data and Info will be invoked in that
order since that's the order they are declared. Still, I'm not sure
how the parameter "100" is passed along the chain and at which stage
the initiation list is invoked....
Just wondering if someone can explain it in details...
Thanks
Recently I came across these codes. I'm trying to figure out why it's
outputing its result in such a way...
The complete codes are:
#include <iostream>
struct Data {
Data(int i_ = 0) : _i(i_)
{
std::cout << "Data: " << _i << std::endl;
}
int _i;
};
struct Info {
Info(Data* d_) {
std::cout << "Info: " << d_->_i << std::endl;
d_->_i = 1;
}
};
struct Base {
Base(const Data& data_) {
std::cout << "Base: " << data_._i << std::endl;
}
};
struct Derived : Base {
Derived(int i_)
:_info(&_data), Base(_data = i_) {
std::cout << "Derived: " << _data._i << std::endl;
}
Data _data;
Info _info;
};
int main()
{
Derived d(100);
}
and if copy and run it, the outputs are:
Data: 100
Base: 100
Data: 0
Info: 0
Derived: 1
I'm expecting the constructor of Base is invoked first since it's base
class. Then the constructor of Data and Info will be invoked in that
order since that's the order they are declared. Still, I'm not sure
how the parameter "100" is passed along the chain and at which stage
the initiation list is invoked....
Just wondering if someone can explain it in details...
Thanks