Thứ Bảy, 1 tháng 8, 2009

C++: data member initialization

Assume we have this class:
class A
{
public:
A(int x, int y, char z);
void getValues(int &x, int &y);
private:
int a;
int b;
const char c;
};

void A::getValues(int &x, int &y)
{
x = a; y = b;
}

The questions are:
1. How to initial constant data member c ?
2. How to initial a and b ?

And here are the answers:
1. Since
c is a constant, the ONLY way to init c is:
A::A(int x, int y, char z) : c(z)
{
// do sth
}

2. There are 2 ways:
- The 1st one
A::A(int x, int y, char z) : a(x), b(y), c(z)
{
//do sth
}
- The 2nd one
A::A(int x, int y, char z) :c(z)
{
a = x;
b = y;
//do sth
}

Then, here are couple of questions
2.1. What is the different b/w 2 above methods?
---> The 1st one is faster, because there's no need to create default values for
a and b before assign real value to it like the 2nd one.

2.2. In the 1st method, can we reverse order like this
A::A(int x, int y, char z) : b(y), a(x), c(z)
{
//do sth
}
--> It depends on compiler.
* Using GNU C++ compiler, there is a warning:
..\FooBar.cc:35: warning: `A::b' will be initialized after
..\FooBar.cc:34: warning: `int A::a'
..\FooBar.cc:40: warning: when initialized here

This is because
a is declared before b (in class declaration), so compiler expects a stands before b in initialized-list.
The result of
getValues() is correct when executed in this case.
* Using C++ compiler for ALU (OneBTS) project, however,
getValues() returns strange values.

=> Keep in mind the precedence of data member in class declaration and initialized-list, because a mistake in this will lead to un-expected result.

Không có nhận xét nào:

Đăng nhận xét