473,569 Members | 2,436 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 interdependenci es. 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
"interdependenc y"?

Many thanks!

Apr 25 '07 #1
8 2432
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 interdependenci es. 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
"interdependenc y"?
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 interdependenci es, I don't think I have ever come
across a situation where this was a problem.
Apr 25 '07 #2
In message <11************ *********@s33g2 000prh.googlegr oups.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 interdependenci es. 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
"interdependen cy"?

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.c omwrote:
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 interdependenci es. 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
"interdependenc y"?
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.c omwrote:
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 objektorientier ter Datenverarbeitu ng
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 interdependenci es. 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
"interdependenc y"?
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
9448
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, int b=1, int c=1) : _a(a), _b(b), _c(c) {}
106
5506
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 same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an...
15
1529
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. Student kasia = Student(100); I assume these two are equivalent. But I always use former way.
7
1658
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
3516
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 following (with incomplete succes): I want in a given namespace Parameters a list of "initializers" (which are objects derived from a simple interface...
7
2487
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 assume that the following code is exceptions safe? Assuming that the constructor of A, B or C may throw? Can I assume that B is created after the...
4
3697
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 value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for...
10
2596
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; class X { public: int value() const { return val; }
15
7845
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
7703
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7926
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7679
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7983
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5223
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3657
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.