473,765 Members | 2,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Quick question about initializing

Given a simple class like

class test {
private:
size_t size_;
int* data_;
public:
test(size_t s)
: size_(s), data_(new int[s]
{ /* ... */ };
};

I'm curious as to whether there's any differance if I change the
initialization list to:

: size(s), data_(new int[size_])

if we disregard the possible trouble that might cause if I happened to
declare data_ first?

--
Erik Wikström

Nov 15 '06 #1
2 1905


It's also important to know the order in which the initializers will be
evaluated. For example, the following definition will cause problems:
class Thingy : public BaseThingy {
public:
Thingy(int endpoint_, int count_) : last(endpoint_) , BaseThingy(),
first(last - count_) { }
private:
int first;
int last;
};
The reason this is a problem is that initializers in the constructor
are not executed in the order they are listed, but rather the base
class is always initialized first, followed by the other member
variables in the order those variables are declared in the class
definition. (Then the body of the constructor will be executed after
all the members are initialized.) Thus the three initializers in the
constructor for Thingy will be executed in this order:
BaseThingy() // The base class constructor
first(last - count_)
last(endpoint_)
The problem occurs when initializing the member first, as the
expression calculating the value for first contains a reference to
last-but last has not been initialized yet!

The recommended practice is to always list the initializers in the
order they will be executed.

....

Afterwards it was mentioned also this:

However, I disagree that having a long list of initialized attributes
is necessarily bad. For example, const and reference members must have
initializers. Also, for many C++ experts (see for example Scott Meyers'
Effective C++, Item #12), using initializers for member variables is
the preferred practice for cases where an initializer is possible and
the expressions necessary for producing the constructor arguments don't
make the code unsafe or unreadable. The main reason for this is
efficiency.

I found the texts from:
http://www.physicsforums.com/archive...p/t-67914.html

If you would have data_ before size_ in the attribute list like this:

class test {
private:
int* data_; // <---
size_t size_;

public:
test(size_t s)
: size_(s), data_(new int[s]
{ /* ... */ };
};
then size_ would not have been initialized, when data_ is initialized:
: size_(s), data_(new int[size_])
-You would initialize data_ with an uninitialize size_.

size_ would be initialized after data_ is initialized (with an
uninitialized size_).
But your current code might work ok.
I hope that is the way it goes.

Nov 15 '06 #2

<er****@student .chalmers.sewro te in message
news:11******** ************@b2 8g2000cwb.googl egroups.com...
Given a simple class like

class test {
private:
size_t size_;
int* data_;
public:
test(size_t s)
: size_(s), data_(new int[s]
{ /* ... */ };
};

I'm curious as to whether there's any differance if I change the
initialization list to:

: size(s), data_(new int[size_])

if we disregard the possible trouble that might cause if I happened to
declare data_ first?
Also disregarding the errors? :-) (You left off the closing parentheses in
the first example, and the ending underscore for size_ in the second.)

I guess you're just asking if using s versus size_ makes a difference. In
this case, probably not. (There might be a small performance difference on
some compilers, especially in unoptimized (i.e., debug) code, but I doubt
it. You could check the assembler output from each to see what yours does.)

But as long as size_ is declared before data_, it will get initialized
first, so there should be no problems. (I prefer the first version, though,
just in case the declaration order DOES get changed!)

-Howard


Nov 15 '06 #3

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

Similar topics

14
1503
by: Fred H | last post by:
I'm reading a STL book right now, and there I've picked up the folowing syntax: class C { private: int value; public: C(int initValue) : value(initValue) { } }
24
3820
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
47
2656
by: sunglo | last post by:
Some time a go, in a discussion here in comp.lang.c, I learnt that it's better not to use a (sometype **) where a (void **) is expected (using a cast). Part of the discussion boiled down to the rule: if I cast a (sometype **) to a (void **) I am making a number of assumptions about the implementation's (void **) representation and length. Specifically, if I do the above cast I'm assuming that a (sometype **) and a (void **) have the same...
3
2554
by: Jess | last post by:
Hello, I've been reading Effective C++ about multiple inheritance, but I still have a few questions. Can someone give me some help please? First, it is said that if virtual inheritance is used, then "the responsibility for initializing a virtual base is borne by the most derived class in the hierarchy". What does it mean? Initializing base class is usually done automatically by the compiler, but a derived class can invoke the base...
13
1487
by: Aarti | last post by:
I have a very elementary question about pointers. Please pardon me for my ignorance of C int main() { int* i; *i = 1 //at times this may give me a core dump. const char* str = "test"; //This seems to be a valid construct. }
5
6289
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is JDK 6 downloadable from http://java.sun.com/javase/downloads/index.jsp. I will be using JDK 5(update 8)
0
3907
by: r035198x | last post by:
Inheritance We have already covered one important concept of object-oriented programming, namely encapsulation, in the previous article. These articles are not articles on object oriented programming but on Java programming but I will cover all the important aspects of object oriented programming as Java has full support for object-oriented programming even though it is not a fully object-oriented language (in the sense that you can write...
13
2340
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other initialization takes place." Does this mean all non-local objects will be zero-initialized before they are initialized by their initializers(if they have)? For example: int g_var = 3; int main() {}
0
10007
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9957
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9835
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7379
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.