473,396 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

order of object initialization and the use of constructor initializer

Hello,

When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer. Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?

Many thanks!

Apr 25 '07 #1
8 2418
Jess wrote:
Hello,

When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer. Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?
The order of construction is reversed for destruction. If you have
multiple constructors for the class, the order of construction is always
the same, as you said, no matter how the initializers are ordered.

Some compilers will issue a warning if the initializer list is not
consistent with the order of member declarations.

As for issues of interdependencies, I don't think I have ever come
across a situation where this was a problem.
Apr 25 '07 #2
In message <11*********************@s33g2000prh.googlegroups. com>, Jess
<wd***@hotmail.comwrites
>Hello,

When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer.
They *still* get initialised in the order of declaration, but using the
default constructor (provided it exists).

And you have no choice, if the members don't have a default constructor,
or their assignment operator is not defined, or it has a different
effect from the constructor.
Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?

Many thanks!
--
Richard Herring
Apr 26 '07 #3
If I have a class like:

class A{
int x;
int y;
string z;
B b;
A () : x(0), y(0) { x = 1;}
}

Then if I have a code that is "A a;" then I think the following
happens:
-- A() is called
-- x -0, y -0
-- z becomes null string
-- b is initialized by calling B's constructor
-- body of A() is entered, and x -1.

Is this right?
If A() is changed to:
A () : y(0), x(0) { x = 1;}

Then will the compiler complain? Thanks

Jess

Apr 27 '07 #4
Jess wrote:
If I have a class like:

class A{
int x;
int y;
string z;
B b;
A () : x(0), y(0) { x = 1;}
}

Then if I have a code that is "A a;" then I think the following
happens:
-- A() is called
-- x -0, y -0
-- z becomes null string
... because that's how the default string c-tor behaves.
-- b is initialized by calling B's constructor
".. by calling B's _default_ constructor"
-- body of A() is entered, and x -1.
1 -x
>
Is this right?
Pretty much.
If A() is changed to:
A () : y(0), x(0) { x = 1;}

Then will the compiler complain? Thanks
I don't know, you need to ask the compiler.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 27 '07 #5
On Apr 25, 12:07 pm, Jess <w...@hotmail.comwrote:
When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer. Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?
There are cases where one attribute needs to be passed into a
superclass constructor or into another attribute's constructor and
these can cause problems.

Where you're passing between attributes then you should order them
correctly in the class definition. Where you have to pass into the
superclass I've done something like this (heavily abridged):

// Super's constructor needs an int pointer to use
class Super { Super( int * ); };

// We store the int here
class Holder { int m_attribute; };

// We can now get the int constructed before Super needs it
class Sub : Holder, Super { Sub(); };

// Pass the int to Super
Sub::Sub()
: Holder(), Super( &m_attribute ) {}

As I understand it the order of the super-classes in the definition of
Sub is important, not the order of the calls in the definition of
Sub's constructor. This is analogous to the case with the attribute
order in the class definition.
K

Apr 27 '07 #6
On Apr 27, 5:11 am, Jess <w...@hotmail.comwrote:
If I have a class like:
class A{
int x;
int y;
string z;
B b;
A () : x(0), y(0) { x = 1;}
}
Then if I have a code that is "A a;" then I think the following
happens:
-- A() is called
-- x -0, y -0
-- z becomes null string
-- b is initialized by calling B's constructor
-- body of A() is entered, and x -1.
Is this right?
If A() is changed to:
A () : y(0), x(0) { x = 1;}
Then will the compiler complain? Thanks
It might issue a warning, but the code is legal, and does
exactly what the previous code does.

The only time this is a problem is if you write something like:

A::A() : y( 0 ), x( y ) { x = 1; }

In this case, you actually have undefined behavior, because you
try to initialize x with y before having initialized y.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 27 '07 #7
Jess <wd***@hotmail.comwrote:
When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer. Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?
Here is a contrived example, but it demonstrates the point:
#include <iostream>

struct Foo {
const int c;
int i;

Foo(int x) : c(x), i(2 * c) { }
};
struct Bar {
int i;
const int c;

Bar(int x) : c(x), i(2 * c) { }
};
int main()
{
using std::cout;

Foo f(3);
cout << f.c << ", " << f.i << '\n';

Bar b(3);
cout << b.c << ", " << b.i << '\n';
}
Output:
3, 6
3, 8529120
In Foo, first the const int c is initialized with the value of 3, then
the int i is initialized with the value of (2*3).

In Bar, since i was declared before c, then i's initialization occurs
first. At this point the value of c is garbage (and thus reading it is
really undefined behavior), so i is initialized with 2*garbage before c
is initialized.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 27 '07 #8
Many thanks for your explanations!

Jess

Apr 28 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Michael McKnerney | last post by:
Hi, It seems I can influence how a base class is initialized beyond the 'normal' manner and I was wondering if someone can tell me why this. Here's my example. class A { public: A(int a=1,...
106
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the...
15
by: Tony Johansson | last post by:
Hello! Assume I have a class named Student and I instansiate an object called kasia in this way. Student kasia(100); What the difference if I instead instansiate this kasia in this way....
7
by: xllx.relient.xllx | last post by:
Q1: What happens when you apply parenthesis to the class type name? Is the constructor for the class called and returns an object?, or what? in main...: MyClass(); // end
1
by: Sandro Bosio | last post by:
Hello everybody, my first message on this forum. I tried to solve my issue by reading other similar posts, but I didn't succeed. And forgive me if this mail is so long. I'm trying to achieve the...
7
by: Peter | last post by:
I know the order of construction of member and base class objects. My question is the following: Is the order of evaluation of argument lists for these constructors also defined? E.g. can I...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
10
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; class X { public: int value() const { return val; }
15
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.