Gotchas in the C++ programing language

来源:互联网 发布:java基本数据类型存储 编辑:程序博客网 时间:2024/06/05 03:10

Initializer lists

In C++, it is the order of the class inheritance and of the member variables that determine the initialization order, not the order of an initializer list:



#include 
<iostream>

class CSomeClass
{
public:
CSomeClass(
int n)
{
std::cout 
<< "CSomeClass constructor with value ";
std::cout 
<< n << std::endl;
}

}
;

class CSomeOtherClass
{
public:
CSomeOtherClass() 
//In this example, despite the list order,
: obj2(2), obj1(1//obj1 will be initialized before obj2.
{
//Do nothing.
}

private:
CSomeClass obj1;
CSomeClass obj2;
}
;

int main(void)
{
CSomeOtherClass obj;
return 0;
}

 
原创粉丝点击