Initializing members with members - c++

This is a problem I come across often. The following examples illustrates it:
struct A {
int m_SomeNumber;
};
struct B {
B( A & RequiredObject );
private:
A & m_RequiredObject;
};
struct C {
C( );
private:
A m_ObjectA;
B m_ObjectB;
};
The implementation of the constructor of C looks something like this:
C::C( )
: B( m_ObjectA )
{ }
Since the order of initialization is not defined, m_ObjectA might be uninitialized when the constructor of m_ObjectB is called, resulting in undefined behavior. One way to force a certain order of initialization would be to make the members pointers and initialize them in the constructor body, thus forcing the correct order, but this is ugly for several reasons. Is there any way to force a certain initializtion order using the initialization-list of the constructor? If not, do you have any other suggestions how to handle this.

Since the order of initialization is not defined
On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization list order match the order of the declarations to avoid nasty surprises).

Related

Class member initialization order, C++ [duplicate]

This question already has answers here:
Order of member initialization list [duplicate]
(2 answers)
Closed 5 years ago.
All old and modern C++ books and experts state to initialize class members by their declaration order. But neither explains what if I don't??
I am not talking about classes with members of const types or smth.. just plain simple class.
Consider the sample:
class A
{
int n;
std::vector<double> VD;
char c;
public:
A():
VD(std::vector<double>(3)),
c('a'),
n(44)
{
}
};
Whats the difference of written code and the one with same order in which they are declared???
Whats the difference of written code and the one with same order in which they are declared???
If members don't depend on each other's initialization order, there is no difference whatsoever. But if they do, then a member initialization list may be telling a lie.
Many a programmer were bitten by this, when they thought their constructors were written correctly, but in fact they had undefined behavior on their hands.
Consider this simple case:
struct foo {
int _a;
int _b;
foo(int b) : _b(b), _a(2 * _b) {}
};
What's _a in the above example? If you answer anything but "the behavior is undefined because _b is used initialized", you'd be wrong.
But neither explains what if I don't?
Programmers have no control over it: the order in which you list members in the initialization list has no effect on the actual order of initialization. The compiler ignores the order of items on the list, and re-orders the expressions to match declaration order.
Here is a short example to illustrate this point:
struct Foo {
Foo(const char *s) { cout << "Init " << s << endl; }
};
struct Bar {
Foo a;
Foo b;
Foo c;
Bar() : c("c"), b("b"), a("a") {
}
};
The above prints
Init a
Init b
Init c
even though initialization lists the items in opposite order.
Demo.
There ought to be absolutely no difference in the generated assembly, although the "as-if" rule might get in the way.
Conceptually at least, n is initialised before c.
Reference: http://en.cppreference.com/w/cpp/language/as_if
You can't change initialisation order - it's the order the members appear in the class - the order in the initialisation list is not significant, though compilers may warn if the two orders don't match up.
I think there are two reasons to order them properly.
The same order as they are declared makes the code more readable, especially when you want to add or remove some more variables.
The order they are declared indicates their order in the memory. You have more locality when you initialize the variables.
It depends on how the members are used. If there is a dependency then order must be followed.
Consider below example.
class x{
size_t n;
char * ch; // the size of dynamic char array depends on n
}
Here, initializing in different order will result in undefined behavior
Other than this reason, of course readability and uniformity matters from coding guidelines POV.

c++ variable assignment, is this a normal way..?

This may be a silly question, but still I'm a bit curious...
Recently I was working on one of my former colleague projects, and I've noticed that he really loved to use something like this:
int foo(7);
instead of:
int foo = 7;
Is this a normal/good way to do in C++ language?
Is there some kind of benefits to it? (Or is this just some silly programming style that he was into..?)
This really reminds me a bit of a good way how class member variables can be assigned in the class constructor... something like this:
class MyClass
{
public:
MyClass(int foo) : mFoo(foo)
{ }
private:
int mFoo;
};
instead of this:
class MyClass
{
public:
MyClass(int foo)
{
mFoo = foo;
}
private:
int mFoo;
};
For basic types there's no difference. Use whichever is consistent with the existing code and looks more natural to you.
Otherwise,
A a(x);
performs direct initialization, and
A a = x;
performs copy initialization.
The second part is a member initializer list, there's a bunch of Q&As about it on StackOverflow.
Both are valid. For builtin types they do the same thing; for class types there is a subtle difference.
MyClass m(7); // uses MyClass(int)
MyClass n = 3; // uses MyClass(int) to create a temporary object,
// then uses MyClass(const MyClass&) to copy the
// temporary object into n
The obvious implication is that if MyClass has no copy constructor, or it has one but it isn't accessible, the attempted construction fails. If the construction would succeed, the compiler is allowed to skip the copy constructor and use MyClass(int) directly.
All the answers above are correct. Just add that to it that C++11 supports another way, a generic one as they say to initialize variables.
int a = {2} ;
or
int a {2} ;
Several other good answers point out the difference between constructing "in place" (ClassType v(<constructor args>)) and creating a temporary object and using the copy constructor to copy it (ClassType v = <constructor arg>). Two additional points need to be made, I think. First, the second form obviously has only a single argument, so if your constructor takes more than one argument, you should prefer the first form (yes, there are ways around that, but I think the direct construction is more concise and readable - but, as has been pointed out, that's a personal preferance).
Secondly, the form you use matters if your copy constructor does something significantly different than your standard constructor. This won't be the case most of the time, and some will argue that it's a bad idea to do so, but the language does allow for this to be the case (all surprises you end up dealing with because of it, though, are your own fault).
It's a C++ style of initializing variables - C++ added it for fundamental types so the same form could be used for fundamental and user-defined types. this can be very important for template code that's intended to be instantiated for either kind of type.
Whether you like to use it for normal initialization of fundamental types is a style preference.
Note that C++11 also adds the uniform initialization syntax which allows the same style of initialization to be used for all types - even aggregates like POD structs and arrays (though user defined types may need to have a new type of constructor that takes an initialization list to allow the uniform syntax to be used with them).
Yours is not a silly question at all as things are not as simple as they may seem. Suppose you have:
class A {
public:
A() {}
};
and
class B {
public:
class B(A const &) {}
};
Writing
B b = B(A());
Requires that B's copy constructor be accessible. Writing
B b = A();
Requires also that B's converting constructor B(A const &) be not declared explicit. On the other hand if you write
A a;
B b(a);
all is well, but if you write
B b(A());
This is interpreted by the compiler as the declaration of a function b that takes a nameless argument which is a parameterless function returning A, resulting in mysterious bugs. This is known as C++'s most vexing parse.
I prefer using the parenthetical style...though I always use a space to distinguish from function or method calls, on which I don't use a space:
int foo (7); // initialization
myVector.push_back(7); // method call
One of my reasons for preferring using this across the board for initialization is because it helps remind people that it is not an assignment. Hence overloads to the assignment operator will not apply:
#include <iostream>
class Bar {
private:
int value;
public:
Bar (int value) : value (value) {
std::cout << "code path A" << "\n";
}
Bar& operator=(int right) {
value = right;
std::cout << "code path B" << "\n";
return *this;
}
};
int main() {
Bar b = 7;
b = 7;
return 0;
}
The output is:
code path A
code path B
It feels like the presence of the equals sign obscures the difference. Even if it's "common knowledge" I like to make initialization look notably different than assignment, since we are able to do so.
It's just the syntax for initialization of something :-
SomeClass data(12, 134);
That looks reasonable, but
int data(123);
Looks strange but they are the same syntax.

When should we not use initialization list in the constructor?

Can someone please quote an example code when we should not use initialisation list in the constructor and how that can be overcome with assignment?
I am looking for an example for the below statement
This might happen when your class has two constructors that need to initialize the this object's data members in different orders. Or it might happen when two data members are self-referential. Or when a data-member needs a reference to the this object, and you want to avoid a compiler warning about using the this keyword prior to the { that begins the constructor's body (when your particular compiler happens to issue that particular warning). Or when you need to do an if/throw test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your this members.
I believe the main concept that the author of your statement was referring to is the fact that calls made to variables in the initialisation list occur not in the order you see them in the initialisation list, but in the order the variables are listed in the class definition.
That means
if you have two different constructors which use initialisation lists, they must initialise them in the same sequence
your control over sequencing (which may be important if you have mutually-dependent members) is limited
I'd recommend taking a look at Scott Meyer's Effective C++ which covers this (amongst many, many other useful and informative topics).
Here are some examples:
This might happen when your class has two constructors that need to
initialize the this object's data members in different orders.
class Example1 {
public:
Example1(std::string decoded, std::string encoded)
: decoded_(decoded),
encoded_(encoded) {}
explicit Example1(std::string encoded)
: decoded_(), // Can't use "decoded_(Decode())" since "encoded_" isn't initialised
encoded_(encoded) {
decoded_ = Decode(); // Assign here instead of initialising
}
private:
std::string Decode(); // decodes class member "encoded_"
std::string decoded_, encoded_;
};
In this example, decoded_ will always be initialised before encoded_ since that's the order in which they are declared in the class, even if we swap their order in the initialisation list.
Or when a data-member needs a reference to the this object, and you
want to avoid a compiler warning about using the this keyword prior to
the { that begins the constructor's body (when your particular
compiler happens to issue that particular warning).
class Example2 {
public:
Example2() : functor_() {
functor_ = std::bind(&Example2::Do, this);
}
private:
void Do();
std::function<void()> functor_;
};
Here, functor_ needs to use this when it is initialised/assigned. If we were to intialise functor_ in the initialisation list, the this pointer would be referring to an object which at that point wasn't fully initialised. That could be safe depending on the particular circumstances, but the foolproof option is to defer setting functor_ until inside the constructor body, by which point this does refer to a fully-initialised object.
Or when you need to do an if/throw test on a variable (parameter,
global, etc.) prior to using that variable to initialize one of your
this members.
class Example3 {
public:
Example3(int force, int acceleration)
: force_(force),
acceleration_(acceleration),
mass_(0) {
if (acceleration_ == 0)
throw std::exception("Can't divide by 0");
mass_ = force_ / acceleration_;
}
private:
int force_, acceleration_, mass_;
};
Hopefully this is self-explanatory.
I'm not sure what is meant by
when two data members are self-referential
so I can't give an example for that I'm afraid.

Initialization order with constructors in C++

By instantiating an object in C++ with the following class I get a segmentation fault or aborts, depending on the order declaring member variables. E. g. putting mMemberVar and mAnotherMemberVar after mAnotherCountVar results in a segfault. From this listing I removed a std::ofstream from the member variables, which caused the segmentation fault independent of its position.
I think the order is not directly the problem, but what do you think could the reason be? This class is part of a huge project, but this in this class is the place, where the error appeared the first time.
class COneClass : public IInterface
{
public:
COneClass();
virtual ~COneClass();
static const unsigned int sStaticVar;
static const unsigned int sAnotherStaticVar;
private:
COneClass();
COneClass(const COneClass& );
COneClass& operator=(const COneClass& );
int mMemberVar;
int mAnotherMemberVar;
bool mIsActive;
bool mBoolMemberVar;
bool mAnotherBoolMemberVar;
unsigned int mCountVar;
unsigned int mAnotherCountVar;
};
COneClass::COneClass() :
mMemberVar(0),
mAnotherMemberVar(0),
mIsActive(false),
mBoolMemberVar(false),
mAnotherBoolMemberVar(false),
mCountVar(sStaticVar),
mAnotherCountVar(sAnotherStaticVar)
{
}
the class members are initinised by the order they are declared. the order in the init list does not matter. In your case it's this order:
mMemberVar -> mAnotherMemberVar -> mIsActive -> mBoolMemberVar -> mAnotherBoolMemberVar -> mCountVar -> mAnotherCountVar;
Perhaps it is a case of the "static initialization order fiasco", http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.16, as a result of initializing mCountVar and mAnotherCountVar with static members?
You could init to zero in the list and then assign in the body of the constructor.
Could be "static initialization order fiasco" judging by the fact that you have public static variables and a private constructor (speaking of which how can you have a public and private definition of the constructor???). These signs indicate the possibility that there is a dependency with other classes here.
The members’ constructors are called before the body of the containing class’ own constructor
is executed. The constructors are called in the order in which they are declared in the class rather
than the order in which they appear in the initializer list.
To avoid confusion, it is best to specify the initializers in declaration order.
The member destructors are called in the reverse order of construction every thing work properly
class MyClass//**1: mem-init**
{
private:
long number;
bool on;
public:
MyClass(long n, bool ison) : number(n), on(ison) {}
};
MyClass(long n, bool ison) //2 initialization within constructor's body
{
number = n;
on = ison;
}
There is no substantial difference between the two forms in the case of MyClass's constructor. This is due to the way mem-initialization lists are processed by the compiler. The compiler scans the mem-initialization list and inserts the initialization code into the constructor's body before any user-written code. Thus, the constructor in the first example is expanded by the compiler into the constructor in the second example. Nonetheless, the choice between using a mem-initialization list and initialization inside the constructor's body is significant in the following four cases:
Initialization of const members
Initialization of reference members
Passing arguments to a constructor of a base class or an embedded object
Initialization of member objects
I think the whole class is not directly the problem. Can you produce a minimal code that crashes just by using this class? It seems to me that the problem is somewhere else in your code base.
However, you may add a bool Invariant() const; function to that class and call it (only in debug builds) with assert(Invariant()); at the end of your constructor and on entering and exiting all your public functions. This might help you to "crash early, crash often" and hence point you to some of the problematic code.
This doesn't look like your real code. But be aware in your real code, that class members are constructed in the order they are defined in the class, REGARDLESS of the order of the initializer list in the constructor. Given that you mention changing the order of the members in the class affects the problem, this might be what's wrong. For example, your code might do something like this:
class MyClass {
public:
const int member1;
const int member2;
MyClass() {
: member2(0),
: member1(member2) // ERROR: this runs first because member1 is defined first
// member2 not yet constructed; assigns undefined value to member1
{}
};
There's nothing in the code you've posted which is in any way abnormal. Either something in the IInterface constructor is failing, or something else entirely is going wrong. Perhaps you've a buffer overflow somewhere which is reading the data you've changing the structural order of.

Initializing in constructors, best practice?

I've been programming in C++ a while and I've used both methods:
class Stuff {
public:
Stuff( int nr ) : n( nr ) { }
private:
int n;
}
Or
class Stuff {
public:
Stuff( int nr ) {
n = nr;
}
private:
int n;
}
Note: This is not the same as this, similar but not the same.
What is considered best practice?
Initializer lists are preferred. See FAQ 10.6
One big advantage to using initializers: If an exception is thrown anywhere within the initializer list, the destructors will be called for those members that had already been initialized -- and only for those members.
When you use the contructor body to initialize the object, it's up to you to handle exceptions properly and unwind the object as appropriate. This is usually much harder to get right.
Use the initializer list when possible. For an int, it doesn't matter much either way, but for a more complex member object, you'd end up with the default constructor of the object being called, followed by an assignment to that object, which is likely to end up being slower.
Plus, you have to do it that way anyway for const members or members which don't have a default constructor.
If possible, use the first version.
The first is initializing using intializer lists, and actually calls the constructors of the members.
The second is assignment. If n was of a type with a default constructor, it the would have already been called, and then you'd be assigning to it. If n didn't have a default constructor, you'd be forced to use the first type. Likewise if n was a reference: int &n.
If there are no constructors of you members that directly take one of the parameters to your constructor, it may be worthwhile to add private static functions that can do the conversion for you.
I generally try to do the initializer list when I can. For one thing, this makes it explicit that you are initializing code in the constructor. const memebers have to be initialized this way.
If you just put code in the constructor's body, it is quite possible someone may decide to come along and move a big chunk of it into a non-constructor "setup" routine later.
It can be taken overboard though. I have a coworker who likes to create classes that have 2 pages of initilizer code, no constructor code, and perhaps 2 pages for the entire rest of the class' code. I find that really tough to read.
I want to add that you don't need to declare the initializer list on the Header (.h). It can be done at the implementation of the constructor (which is very common).
So then:
//Stuff.h
class Stuff {
public:
Stuff( int nr );
private:
int n;
}
//Stuff.cpp
Stuff::Stuff(int nr)
: n(nr)
{
//initalize complex members
}
is legal and imo concentrates the initialization of fields where it matters. Sometimes we need to initialize complex members in the body, so you have your initializer list and the complex initialization all in the .cpp file.
The second option is not initialization but assignment. With types that have user defined default constructors, the second option will call the default constructor and later on call the assignment operator (whether user defined or not) to assign the value.
Some types cannot be default initialized: If you have an attribute without default constructor, hold references (constant or not) or have constant attributes they must be initialized in the initializer list.
Arrays can be value-initialized in the initialization list, but not in the constructor body:
class X {
public:
X() : array() {} // value-initializes the array
// equivalent to:
// X() { for ( int i = 0; i < 10; ++i ) array[i]=0; }
private:
int array[10];
};
For POD types, you can value-initialize them in the initialization list but not inside the brackets:
class X {
public:
X() : pod() {} // value-initializes
// equivalent to (but easier to read and subtly faster as it avoids the copy):
// X() { pod = {}; }
private:
PODType pod;
};
Finally, some classes offer functionality through the use of constructors that will be more complex (if achievable) after default construction.
class X
{
public:
X() : v(10) {} // construct a vector of 10 default initialized integers
// equivalent to:
// X() { for ( int i = 0; i < 10; ++i ) v.push_back(0); }
private:
std::vector<int> v;
};
Last, whenever they are in fact equivalent, initialization lists are more idiomatic in C++.