473,785 Members | 2,317 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class object initialisation

A
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 initalisation list for initialising data
members of a class?
Regards
Adi

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.516 / Virus Database: 313 - Release Date: 1/09/2003
Jul 19 '05
106 5612
tom_usenet wrote:
[SNIP]
Yes, when you don't give an initializer, it is still initialized.
"Initialize r" and "Initialization " are different things. Even if you
don't use an initializer, initialization still takes place.
Initialization is the action. An action of giving a determined value to
some object. If this is not done, well, then it is not initialized.

This is a sort of foxymoron. A smart way of telling that if I do not
initialize (give a value) to an object I still initialize (give a value) to
an object. Something is not right here. Later of course we say: well, we
have initialized the value but..., hm, khm, we still cannot use it until we
give a value to it. Something is not right. We have to be brave enough to
say: no initialization happens. The POD is not necessarily itself. That
int might not be int! How could we say: it is initialized? If the standard
says that - it is wrong. We can vote to say the Earth is flat and the fixed
center of the universe it will still not be. :-)
The lvalue to rvalue thing applies to things that have been
initialized too:

int* p = new int;
delete p; //p now indeterminate (but obviously initialized)
Nope. It is invalid, not indetermined.
int* q = p; //error, lvalue-to-rvalue conversion


Totally different case.

And it is still moving... ;-)

--
WW aka Attila
Jul 19 '05 #41
Gary Labowitz wrote:
[SNIP]
This i, if it has an automatic storage, is not initialized.
Accessing it for anything else then writing (assigment or
initialization)
If it has not been initialized, how can it be initialized later?
I thought that initialization can only occour when a variable
is created. Afterwards it is always assignment.


Would this allow for assigning a value to a const variable during
construction of the object containing the variable?


Nope. My wording was not clear.
(Or does it have
to be initialized in the declaration statement?)
It has to be initialized in an initializer list in the a class, or in case
of a static member in its definition (or inside the class if it is an
integral constant). "Normal" constant variables has to be initialized at
their definition.
Assigning the initial value of a variable (even const, called
"final") is allow in (for example) Java.
OK. In C++ it is called initialization. A const value can only be
initialized and must be initialized. You cannot assign a new value to it
(whatever value means for it).
They appear to keep track of
a variable's state as "uninitiali zed" and define the assigning of a
value during construction as initialization. Does C++ do this?
Nope. The closest thing to this in C++ is the way static variables in a
function scope are initialized. But those are the exception, C++ does nto
keep track of initialized state - in the name of the "cause of all evil",
optimization. :-)
If it
did, then calling a constructor as part of an initialization list is
perfectly valid; and I think it is!


Caling a constructor on the _member_ intiializer list is valid. But not for
the reasons you mention.

--
WW aka Attila
Jul 19 '05 #42
tom_usenet wrote:
[SNIP]
If you choose your words carefully it makes more sense: "If we don't
provide an initializer for a POD, the object is initialized to an
indeterminate value."
Initialization == giving an initial value

not giving an initial value (but leave garbage there) != initialization
"initialize " and "provide an initializer for" are best thought of as
different things. initialize is something the compiler (or exe) does
to a variable. It does it whether you provide an initializer or not.


Yes. But the compiler (or the exe) does *nothing* to uninitialized PODs!

--
WW aka Attila
Jul 19 '05 #43

"Ying Yang" <Yi******@hotma il.com> wrote in message news:3f******** @news.iprimus.c om.au...
If my class does not extend any class then there would be no base class your
referring to. Maybe you mean a default constructor of a class must always be
present when you use an initialisation list. Can you be more clear?


Some constructor has to be defined to use an initializer list (doesn't necessarily
have to be the default). This only makes sense simce the initialization list is
part of the constructor definition syntax.

He said IF you have a base class with no default constructor. If you derive from
the derived constructors need to provide initializers so that a valid constructor can
be invoked.
Jul 19 '05 #44
On Mon, 15 Sep 2003 16:43:58 +0300, "White Wolf" <wo***@freemail .hu>
wrote:
tom_usenet wrote:
[SNIP]
Yes, when you don't give an initializer, it is still initialized.
"Initialize r" and "Initialization " are different things. Even if you
don't use an initializer, initialization still takes place.
Initializati on is the action.


Ok
An action of giving a determined value to
some object.
Who says? Not the standard.

struct A
{
int i;
A(int){}
};

A a(1); // initialized? yes. determinate value? no.
If this is not done, well, then it is not initialized.
Your definition of initialized is wrong. e.g. 6.7/2
"Variables with automatic storage duration (3.7.2) are initialized
each time their declaration*sta tement is executed."

It doesn't say that you initialize them. It says that they are
initialized (maybe by you, maybe by the compiler, maybe by the great
goddess of undefined behaviour).
This is a sort of foxymoron. A smart way of telling that if I do not
initialize (give a value) to an object I still initialize (give a value) to
an object.


Why the use of "I"? The compiler can give a value to an object (aka
initialize it). This value might be indeterminate. Here is an example
of just that (from 8.5.1/8):

"An empty initializer*lis t can be used to initialize any aggregate. If
the aggregate is not an empty class, then each member of the aggregate
shall be initialized with a value of the form T() (5.2.3), where T
represents the type of the uninitialized member. "

Here, "initialize d" means "initialize d by the compiler/runtime",
whereas the "uninitiali zed" means "not directly initialized by an
initializer".
The lvalue to rvalue thing applies to things that have been
initialized too:

int* p = new int;
delete p; //p now indeterminate (but obviously initialized)


Nope. It is invalid, not indetermined.


Ahh, yes, although it might be useful to allow it to fall under 4.1 by
changing the language in both places to "inderminat e value" or
similar.

The standard seems to be a bit sloppy about its use of the word
"initialize " and this could probably do with clearing up...

Tom
Jul 19 '05 #45
On Mon, 15 Sep 2003 16:51:15 +0300, "White Wolf" <wo***@freemail .hu>
wrote:
tom_usenet wrote:
[SNIP]
If you choose your words carefully it makes more sense: "If we don't
provide an initializer for a POD, the object is initialized to an
indeterminate value."
Initializati on == giving an initial value


Indeed, however this doesn't have to involve an initializer.
not giving an initial value (but leave garbage there) != initialization
Nope, the compiler gives an initial value to PODs if you don't bother.
This is also initialization.
"initialize " and "provide an initializer for" are best thought of as
different things. initialize is something the compiler (or exe) does
to a variable. It does it whether you provide an initializer or not.


Yes. But the compiler (or the exe) does *nothing* to uninitialized PODs!


Are you saying that the bytes making up the value representation of a
POD have to be changed for initialization to have occurred? I don't
think the standard backs you on this!

Tom
Jul 19 '05 #46

"foo" <ma*******@axte r.com> wrote in message
news:c1******** *************** **@posting.goog le.com...
"jeffc" <no****@nowhere .com> wrote in message

news:<3f******* *@news1.prserv. net>...
"Erik" <no@spam.com> wrote in message news:bj******** **@news.lth.se. ..
> The basic rule of thumb is that anything that can go in the initialize
list
> should go there. Obviously, you can't put something like this in
there: > if (a)
> i = 2;
> else
> i = 4;

Many, if not most, of those cases can be covered by the ?: operator:
MyClass(int a) : i(a ? 2 : 4) {}


Yeah, maybe simple "if" cases like that, but you can't put logic or

function calls (other than base class constructors) in the initializer list. You
added an expression, not a statement.

There are plenty of things you can put in the initializer list.
You can put functions, additions, conditon logic, and more.


And there are plenty of things you can't. You can put expressions in there,
but you can't put statements in there. You can't call functions (alone),
you can't use for or while loops, you can't... well, you already know what
you can't do.
Jul 19 '05 #47

"Ron Natalie" <ro*@sensor.com > wrote in message
news:3f******** *************** @news.newshosti ng.com...

"jeffc" <no****@nowhere .com> wrote in message

news:3f******** @news1.prserv.n et...

Yep - and sometimes it makes sense to create a function that does more
complex things so that everything is in the initializer list.


And how exactly do you propose calling such a function from the initializer list?


Same way you call any other function.


Yeah, right.
Jul 19 '05 #48

"Ron Natalie" <ro*@sensor.com > wrote in message
news:3f******** *************** @news.newshosti ng.com...

"jeffc" <no****@nowhere .com> wrote in message news:3f******** @news1.prserv.n et...
Many, if not most, of those cases can be covered by the ?: operator:
MyClass(int a) : i(a ? 2 : 4) {}


Yeah, maybe simple "if" cases like that, but you can't put logic or function calls (other than base class constructors) in the initializer list. You
added an expression, not a statement.


Who says you can't have function calls?


You can only have function calls as part of expressions, not statements.
You can't simply call a function such as initialize() as Gianni suggested
(as you well know.)
Jul 19 '05 #49
On Mon, 15 Sep 2003 11:29:54 -0400, "jeffc" <no****@nowhere .com>
wrote:

"Ron Natalie" <ro*@sensor.com > wrote in message
news:3f******* *************** *@news.newshost ing.com...

"jeffc" <no****@nowhere .com> wrote in message

news:3f******* *@news1.prserv. net...
> > Many, if not most, of those cases can be covered by the ?: operator:
> > MyClass(int a) : i(a ? 2 : 4) {}
>
> Yeah, maybe simple "if" cases like that, but you can't put logic orfunction > calls (other than base class constructors) in the initializer list. You
> added an expression, not a statement.


Who says you can't have function calls?


You can only have function calls as part of expressions, not statements.
You can't simply call a function such as initialize() as Gianni suggested
(as you well know.)


I think you completely misunderstood him:

struct A
{
int a;
static int doCalc(int val);
A(int val): a(doCalc(val))
{
}
};

That was exactly the kind of thing that Gianni was suggesting - if you
can't put the logic inline, make a function for it. If your member is
const or a reference, you have no choice but to do so.

Tom
Jul 19 '05 #50

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

Similar topics

1
3940
by: matro | last post by:
hi there, I have the following struct in my class: class CTbStDialog : public CDialog { public: int fooVar, fooVar2; ... //other foo variables...
8
2536
by: jose luis fernandez diaz | last post by:
Hi, I am reading Stroustrup's book 'C++ Programming Language'. In the 10.4.9 section (Nonlocal Store) he says: "A variable defined outside any function (that is global, namespace, and class static variables) is initializated (constructed) before main is invoked . . ." .. . .
11
2559
by: Neil Zanella | last post by:
Hello, When an "std::map<int, int> foobar;" statement appears in a C++ program followed by a statement of the form "foobar;" where nothing has ever been inserted at position 123 into map foobar, the C++ standard states that a new element is created at position 123 and is initialized to zero. That is, in this case, the pair (123, 0) is inserted into the map. I am interested in knowing what the standard says should happen in the
3
1282
by: deancoo | last post by:
I'm hoping this isn't too off topic, but I'm not sure if I've included some of my member functions in the right class. I needed to develop numerous functions to help define object A. These functions currently exist in the class definition for object A. The thing is, there is another object (B) who's job it is to call these functions when the app starts up, defining all possibilities for object A's, then allow future object A's to look up...
13
2075
by: Frederick Gotham | last post by:
I have just been reading 8.5 in the Standard, and am trying to make sense of the different kinds of initialisations. Up until now, I thought of an object as either NOT being initialised (i.e. containing garbage), or being default initialised (i.e. containing the default value for that type). Here are some examples of the former: struct MyStruct {
16
1477
by: silversurfer2025 | last post by:
Hello everyone, once again, I have a very basic problem in C++, which I was not able to solve (maybe because of my Java-Experience or just because it is always the small syntax-things which break my neck in C++)... I would like to have a static variable in class A and change its value from class B (they are not related to each other) For example:
14
2582
by: Jeroen | last post by:
Hi all, I've got a question about writing a library. Let me characterize that library by the following: * there is a class A which is available to the user * there is a class B that is used in severel 'underwater operations' * there is a list which stores objects of class B There are several issues I'm not sure about:
2
1903
by: .rhavin grobert | last post by:
i have (do try to have?) the following... & = breakpoints in debugger // ---------------------------------------------------------------- // cx.h class CX { public: CX(CX* pcx = NULL); virtual ~CX();
13
1656
by: Anarki | last post by:
#include <iostream> using namespace std; class ConstantMember { const int m_const; public: ConstantMember(int cons = 10):m_const(cons){} int getConst() const{ return m_const;} };
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10315
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10083
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
9946
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
7494
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
5379
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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
3645
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.