-Wreorder

Hi all,

I'm working on a project that uses a hash table I wrote a while ago. I'm getting the following warnings (AFAIK, it's not actually affecting anything but I'm curious as to what they are telling me):
warning: 'HashTable<std::__cxx11::basic_string<char> >::bucketsUsed' will be initialized after [-Wreorder]

warning: 'int HashTable<std::__cxx11::basic_string<char> >::tableSize' [-Wreorder]

warning: when initialized here [-Wreorder]
HashTable<Object>::HashTable() : loadFactor(0), bucketsUsed(0), tableSize(3)


Compiled w/:
g++ -std=c++14 -pedantic -Wall -Wextra


What is this telling me?
The variables are listed within the class in a different order than in the initializer list.
It's logical to assume that the member variables will be initialized in the order that they are listed in the member initialization list but that's not the case. Instead they are initialized in the order they appear in the class definition. This can easily lead to bugs if you are not careful.

Let's say you have a class with two variables, a and b. You want to initialize b to a random value between 1-10 and you want a to be ten times that. This is what you might end up with (if you are not aware about the order in which the members are initialized).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A
{
public:
	A();
private:
	int a;
	int b;
};

A::A()
:	b(rand() % 10 + 1),
	a(10 * b)
{
}

Unfortunately this will not work because a has been defined before b in the class definition so a will be initialized first, but at that time b has not yet been initialized. To fix this problem you would have to reorder the definitions of a and b ...
1
2
	int b;
	int a;
... or put the initialization of a inside the constructor body.
1
2
3
4
5
A::A()
:	b(rand() % 10 + 1)
{
	a = 10 * b;
}

To help you avoid these kind of problems compilers will often warn you if the order of initialization is not the same as the order in which the members appear in the member initialization list. In your situation it doesn't really lead to any problems but to get rid of the warning (and to avoid future problems) you should list bucketsUsed after tableSize.
 
HashTable<Object>::HashTable() : loadFactor(0), tableSize(3), bucketsUsed(0)
Last edited on
Topic archived. No new replies allowed.