Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependent classes as other class members

I have a class B that requires an instance of class A to be constructed:

class B
{
    B(A* a); // there is no default constructor
};

Now I want to create a class that contains B as a member, so I also need to add A as a member and provide it to B's constructor:

class C
{
    C() : a(), b(&a) {}
    A a; // 1. initialized as a()
    B b; // 2. initialized as b(&a) - OK
};

But the problem is that if someone occasionally changes the order of the variables definition in the class, it will break

class C
{
    C() : a(), b(&a) {}
    B b; // 1. initialized as b(&a) while "a" uninitialized
    A a; // too late...
};

Is there a good way to resolve this without modifying the classes A and B? Thanks.

like image 871
Roman L Avatar asked Feb 15 '11 21:02

Roman L


1 Answers

Is there a good way to resolve this without modifying the classes A and B?

Turn on compiler warnings; for gcc, this is -Wreorder (which is included in -Wall):

cc1plus: warnings being treated as errors
t.cpp: In constructor 'A::A()':
Line 3: warning: 'A::y' will be initialized after
Line 3: warning:   'int A::x'
Line 2: warning:   when initialized here

Alternatively, use a lint-like tool that detects this.


But the problem is that if someone occasionally changes the order of the variables definition in the class…

Why would they do this? I suspect you're worrying too much about what might happen. Even so, you can leave a comment in the class:

A a;  // Must be listed before member 'b'!
B b;

Don't underestimate the force of well-placed comments. :) Then allow someone who purposefully ignores them to get what they deserve; you are using C++, after all.

like image 73
Fred Nurk Avatar answered Sep 19 '22 21:09

Fred Nurk