473,396 Members | 1,834 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.

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 #1
106 5453
"A" <A@iprimus.com.au> wrote in message
news:3f********@news.iprimus.com.au...
| 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?

Only when you are unable to, e.g. when a complex computation involving
several intermediate variables is needed and a dedicated function doesn't
make sense.

IMO the initialization list should always be preferred.
Regards,
--
http://ivan.vecerina.com
Jul 19 '05 #2

"A" <A@iprimus.com.au> wrote in message
news:3f********@news.iprimus.com.au...
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?


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;
Jul 19 '05 #3
> > 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?


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) {}

/ Erik
Jul 19 '05 #4
Erik wrote:
....
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) {}


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

Jul 19 '05 #5

"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:bj********@dispatch.concentric.net...
Erik wrote:
...
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) {}


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?
Jul 19 '05 #6

"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.
Jul 19 '05 #7

"jeffc" <no****@nowhere.com> wrote in message news:3f********@news1.prserv.net...

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. It behooves you not to use the
yet uninitialized parts of the object being constructed though.
Jul 19 '05 #8

"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 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?
Jul 19 '05 #9
Ying Yang wrote:

Never.
Initialization lists are the only way to *initialize* members of a class
or to specify which constructor from a base class should be used.

No, it's not the only way - as i mentioned you can use an assignment
operator for initialising primitive data members, which is the same as using
an initialization list.


No, you cannot initialize anything with an assignment operator ever.
Assignment operators assign, they don't initialize. If you don't the
difference, you should look it up.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #10
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<7t***************@newsread3.news.pas.earthli nk.net>...
No, it's not the only way - as i mentioned you can use an assignment
operator for initialising primitive data members, which is the same as using
an initialization list.

(NB: This is true for all POD types, not just primitive types.)
No, you cannot initialize anything with an assignment operator ever.
Assignment operators assign, they don't initialize. If you don't the
difference, you should look it up.


int n; // n is not initialized
n = 0; // 0 assigned to n

Using an uninitialized lvalue as an rvalue is undefined (4.1/1). If
assignment doesn't initialize, ever, then

printf("%d\n", n);

results in undefined behavior. I, for one, highly doubt that.

- Shane
Jul 19 '05 #11
Shane Beasley wrote:


int n; // n is not initialized
n = 0; // 0 assigned to n

Using an uninitialized lvalue as an rvalue is undefined (4.1/1).
Using an indeterminate lvalue is undefined. "Uninitialized" is used to
mean "indeterminate" sometimes, apparently even in the standard.
If
assignment doesn't initialize, ever, then
It doesn't. It assigns.

printf("%d\n", n);

results in undefined behavior. I, for one, highly doubt that.


The value is not indeterminate at this point.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #12
A
Ying Yang wrote:

Never.
Initialization lists are the only way to *initialize* members of a class
or to specify which constructor from a base class should be used.

No, it's not the only way - as i mentioned you can use an assignment
operator for initialising primitive data members, which is the same as using an initialization list.


No, you cannot initialize anything with an assignment operator ever.
Assignment operators assign, they don't initialize. If you don't the
difference, you should look it up.


To initialize means you give a variable it's initial value. An assignment
operator can be used to give a variable it's initial value, and it can also
be used to re-assign a variable with a different value, providing the
variable is not defined as constant. The point is, you can initialise data
members via two of the following ways: assignment or an initialisation list.
However, the behaviour of the two is different depending whether is it a
primitive or class type data member you want to initialize. If you don't
agree with my definition of assignment and initialisation then I like to
hear your definitions.


Jul 19 '05 #13
A wrote:

To initialize means you give a variable it's initial value.
Agreed.
An assignment
operator can be used to give a variable it's initial value,
No, it can't. If you believe it can, please give an example.
and it can also
be used to re-assign a variable with a different value, providing the
variable is not defined as constant. The point is, you can initialise data
members via two of the following ways:
Well, you can't give something its initial value twice, so I assume you
mean "one of the following ways".
assignment or an initialisation list.
....But you're still wrong. Assignment does not give an initial value to
something. Assignment can only happen to an existing object. Since the
object must exist prior to the assignment, it clearly has already
received its initial value.
However, the behaviour of the two is different depending whether is it a
primitive or class type data member you want to initialize. If you don't
agree with my definition of assignment and initialisation then I like to
hear your definitions.


Initialization happens when an object is initially constructed.
Assignment can only happen after that time (or not at all, for certain
types of objects).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #14
foo
"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.
Example:

class foo
{
public:
foo(int x, const std::string &Src)
:m_i((x > 3)?Func2(8):x),
m_data((Src == "test")?Func1("good"):Func1(Src)+" test"),
i(m_i)
{
}

private:
std::string Func1(const std::string &Src){return "Hello World " + Src;}
int Func2(int y){return y + 44;}
int m_i;
public:
const std::string m_data;//Needs to be in an initialized list
const int &i; //Needs to be in an initialized list
};

int main(int argc, char* argv[])
{
foo myfoo(2, "bla bla");
cout << myfoo.m_data << endl;
cout << myfoo.i << endl;

system("pause");
return 0;
}
Jul 19 '05 #15
foo
"A" <A@iprimus.com.au> wrote in message news:<3f********@news.iprimus.com.au>...
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


You need to have an item in the initialize list if it's a constant or
a reference data member.
You also need to have the base class constructor in the initializer
list if the base class does not have a default contructor.

I recommend that you always TRY to use the initialize list.

An initializer list may not be appropriate when you have multiple
constructors, and serveral member variables that have common
initialization values with all the constructors.
In such cases, it's common to create an function initializer to
consolidate the logic.
Example:
class car
{
public:
car(){Initialize();}
car(int x){Initialize();}
car(const char* s){Initialize();}
inline void Initialize()
{
QtyWheels = 4;
ID = -1;
Make = "n/a";
}
private:
int QtyWheels;
int ID;
std::string Make;
};
Jul 19 '05 #16
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<LR****************@newsread3.news.pas.earthl ink.net>...
Using an indeterminate lvalue is undefined. "Uninitialized" is used to
mean "indeterminate" sometimes, apparently even in the standard.


"Apparently"? You make it sound like you know the terminology better
than the authors of the standard. Regardless, they chose to use
"initialization" to describe both syntax (direct- and
copy-initialization) and semantics (the act of giving a variable its
first value, even through assignment), and so that's what it means.

- Shane
Jul 19 '05 #17
Shane Beasley wrote:
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<LR****************@newsread3.news.pas.earthl ink.net>...

Using an indeterminate lvalue is undefined. "Uninitialized" is used to
mean "indeterminate" sometimes, apparently even in the standard.

"Apparently"? You make it sound like you know the terminology better
than the authors of the standard. Regardless, they chose to use
"initialization" to describe both syntax (direct- and
copy-initialization) and semantics (the act of giving a variable its
first value, even through assignment), and so that's what it means.


Please show me where in the standard this definition is given.

I know what the intent of the language in the standard is. The
difference between initialization and assignment has been frequently
pointed out by people who helped write the standard, not to mention
Stroustrup himself:

initialization - giving an object an initial value. Initialization
differs from assignment in that there is no previous value involved.
Initialization is done by constructors.
http://www.research.att.com/~bs/glossary.html

So, do you know the terminology better than Bjarne Stroustrup?

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #18
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<dw*****************@newsread4.news.pas.earth link.net>...
Please show me where in the standard this definition is given.
As previously quoted, 4.1/1 clearly states that an lvalue may not be
used as an rvalue unless it was previously initialized. Apparently,

int n;
n = 0;

qualifies as initialization for these purposes. But it's not done via
direct- or copy-initialization syntax in the declaration of n; rather,
it's done via an assignment expression, so called because it performs
assignment.
I know what the intent of the language in the standard is. The
difference between initialization and assignment has been frequently
pointed out by people who helped write the standard, not to mention
Stroustrup himself:

> initialization - giving an object an initial value. Initialization
differs from assignment in that there is no previous value involved.
Initialization is done by constructors.

http://www.research.att.com/~bs/glossary.html

So, do you know the terminology better than Bjarne Stroustrup?


I know that PODs aren't initialized by constructor (indeed, they
needn't be initialized at all, useless as that would be). Short of
saying that he's wrong, my guess is that he's talking about non-PODs,
which accounts for most types (excluding pointers), and about which
he's entirely correct.

As for PODs, consider the following:

// Assign n to x. (That *is* what it does, no?)
template <typename T> void assign (T &x, T n) { x = n; }

int main () {
int i = 0, j;
assign(i, 0);
assign(j, 0);
i = j;
}

If you're right, then either j isn't initialized and this program is
undefined by 4.1/1, or assign(x, n) performs assignment sometimes and
initialization other times -- all with the same code. (It could also
use a better name -- assign_or_initialize, maybe.) More likely,
assign(x, n) performs assignment all the time and initialization
sometimes.

You're free to disagree, I guess. Of course, it doesn't matter what
your opinion (or mine) is; neither of us will learn anything about C++
that we didn't already know before this thread, nor do I think that
either of us will convince the other of his point. To quote somebody:

"Arguing on the Internet is like competing in the Special Olympics...
Even if you win, you're still retarded."

With that, I hereby agree to disagree and resign.

- Shane
Jul 19 '05 #19
Shane Beasley wrote:
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<dw*****************@newsread4.news.pas.earth link.net>...

Please show me where in the standard this definition is given.

As previously quoted, 4.1/1 clearly states that an lvalue may not be
used as an rvalue unless it was previously initialized. Apparently,


No, it says it can't if the object to which the lvalue refers is
"uninitialized". I can't find a definition for that term in the
standard, but I think it's fairly clear that in this context they are
using it to mean "having an indeterminate value". This use of this term
here may be a defect. In my opinion, it's very clear in the standard
itself that "initialization" refers to giving a value to an object when
it is created.

int n;
n = 0;

qualifies as initialization for these purposes.
It qualifies as giving it a determinate value, but initialization only
occurs when an object is created.

>>initialization - giving an object an initial value. Initialization
differs from assignment in that there is no previous value involved.
Initialization is done by constructors.

http://www.research.att.com/~bs/glossary.html

So, do you know the terminology better than Bjarne Stroustrup?

I know that PODs aren't initialized by constructor (indeed, they
needn't be initialized at all, useless as that would be).


Stroustrup seems to be of the opinion that all types have constructors
(though the standard disagrees with him). I believe this has been
discussed here before. See, for example, page 131 of TC++PL3. I think he
was referring to all types here.
Short of
saying that he's wrong, my guess is that he's talking about non-PODs,
which accounts for most types (excluding pointers), and about which
he's entirely correct.

As for PODs, consider the following:

// Assign n to x. (That *is* what it does, no?)
template <typename T> void assign (T &x, T n) { x = n; }

int main () {
int i = 0, j;
assign(i, 0);
assign(j, 0);
i = j;
}

If you're right, then either j isn't initialized and this program is
undefined by 4.1/1, or assign(x, n) performs assignment sometimes and
initialization other times -- all with the same code.
I don't see where you are getting that from. The function clearly does
an assignment. 4.1/1 deals with conversion from an lvalue to an rvalue,
which does not apply in this case. See 8.5.3/5-7:

5 A reference to type "cv1 T1" is initialized by an expression of type
"cv2 T2" as follows:

--If the initializer expression

6
--is an lvalue (but not an lvalue for a bit-field), and "cv1 T1" is
reference-compatible with "cv2 T2," or

--has a class type (i.e., T2 is a class type) and can be implicitly

converted to an lvalue of type "cv3 T3," where "cv1 T1" is refer-
ence-compatible with "cv3 T3" 9) (this conversion is selected by
enumerating the applicable conversion functions (_over.match.ref_)
and choosing the best one through overload resolution
(_over.match_)), then

7 the reference is bound directly to the initializer expression lvalue
in the first case, and the reference is bound to the lvalue result
of the conversion in the second case. In these cases the reference
is said to bind directly to the initializer expression. [Note: the
usual lvalue-to-rvalue (_conv.lval_), array-to-pointer
(_conv.array_), and function-to-pointer (_conv.func_) standard con-
versions are not needed, and therefore are suppressed, when such
direct bindings to lvalues are done. ]
Summarized, when initializing (e.g., through function argument passing)
a reference, if the initializer expression is a lvalue (clearly the case
here) that is reference-compatible with the destination reference type
(also applicable here), the reference is bound directly to the lvalue,
and the usual lvalue-to-rvalue conversion is suppressed. If you need
proof that function argument passing qualifies as initialization, please
see 8.5/1
(It could also
use a better name -- assign_or_initialize, maybe.) More likely,
assign(x, n) performs assignment all the time and initialization
sometimes.

You're free to disagree, I guess. Of course, it doesn't matter what
your opinion (or mine) is; neither of us will learn anything about C++
that we didn't already know before this thread, nor do I think that
either of us will convince the other of his point. To quote somebody:

"Arguing on the Internet is like competing in the Special Olympics...
Even if you win, you're still retarded."
Well, for one thing neither of us is going to win. Which is pretty much
what you said above.

With that, I hereby agree to disagree and resign.


That's a bit premature. Here are a few more quotations to emphasize my
point (that the intent of the standard, if not the precise wording, is
that initialization occurs only at the time of creation):

8.5 Initializers [dcl.init]

1 A declarator can specify an initial value for the identifier being
declared. The identifier designates an object or reference being ini-
tialized. The process of initialization described in the remainder of
_dcl.init_ applies also to initializations specified by other syntac-
tic contexts, such as the initialization of function parameters with
argument expressions (_expr.call_) or the initialization of return
values (_stmt.return_).

The very fact that "Initializers" comes under declarations is a pretty
strong statement about where initialization occurs, I think. The
phrasing of this passage also implies that initialization is done at
object creation.
12.8 Copying class objects [class.copy]

1 A class object can be copied in two ways, by initialization
(_class.ctor_, _dcl.init_), including for function argument passing
(_expr.call_) and for function value return (_stmt.return_), and by
assignment (_expr.ass_). Conceptually, these two operations are
implemented by a copy constructor (_class.ctor_) and copy assignment
operator (_over.ass_).
This again shows the distinction between initialization and assignment
(applied only to classes in this case).

Maybe stronger proof is in there somewhere. I'm kind of tired of looking
for it, though. I'll agree that the standard appears to be not entirely
consistent on this point, but my feeling is that the intent of the
standard is to create a logical distinction between initialization
(which occurs when an object is created) and assignment (which can only
occur when the target already exists).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #20

"Kevin Goodsell" <us*********************@neverbox.com> wrote in message
news:f6*****************@newsread3.news.pas.earthl ink.net...
A wrote:

To initialize means you give a variable it's initial value.
Agreed.
An assignment
operator can be used to give a variable it's initial value,


No, it can't. If you believe it can, please give an example.


int i; //declared but not initialised
i =5; // variable i is initialised with value 5.
and it can also
be used to re-assign a variable with a different value, providing the
variable is not defined as constant. The point is, you can initialise data members via two of the following ways:


Well, you can't give something its initial value twice, so I assume you
mean "one of the following ways".


what are you smoking?
...But you're still wrong. Assignment does not give an initial value to
something. Assignment can only happen to an existing object. Since the
object must exist prior to the assignment, it clearly has already
received its initial value.


Assignment can be used for both objects types and primitive types. And i was
referring to initialising data members of a class type. Again, what are you
smoking?
However, the behaviour of the two is different depending whether is it a
primitive or class type data member you want to initialize. If you don't
agree with my definition of assignment and initialisation then I like to
hear your definitions.



Jul 19 '05 #21
> > 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

You need to have an item in the initialize list if it's a constant or
a reference data member.
You also need to have the base class constructor in the initializer
list if the base class does not have a default contructor.


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?
PPP
Jul 19 '05 #22


Ying Yang wrote:
A wrote:

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.


No. It calls whatever constructor you specify in the initializer list.

My question is when to not use an initalisation list for initialising data members of a class?


Never.
Initialization lists are the only way to *initialize* members of a class
or to specify which constructor from a base class should be used.


No, it's not the only way - as i mentioned you can use an assignment
operator for initialising primitive data members, which is the same as using
an initialization list.


But then it is no longer *initialization*.
It is assignment.

Those are different things.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #23


Ying Yang wrote:


int i; //declared but not initialised
wrong. initialized to an undetermined value. Initialization.
i =5; // variable i is initialised with value 5.


replacing the undetermined value with a determined value. Assignment.

Initialization happens when a variable comes to live. Note: A variable
can also be initialized to an undetermined value! Once a variable
is 'alive', you can't initialize it any more. But of course you
can assign values to it (except in some cases, eg. references).

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #24
> Ying Yang wrote:


int i; //declared but not initialised


wrong. initialized to an undetermined value. Initialization.


disagree.

Initialization of an object or primitive means to give a determined value to
them for the first time.

i =5; // variable i is initialised with value 5.


replacing the undetermined value with a determined value. Assignment.

Initialization happens when a variable comes to live. Note: A variable
can also be initialized to an undetermined value! Once a variable
is 'alive', you can't initialize it any more. But of course you
can assign values to it (except in some cases, eg. references).


In light of the above, this is no longer valid.


Jul 19 '05 #25
Karl Heinz Buchegger wrote:
Ying Yang wrote:


int i; //declared but not initialised


wrong. initialized to an undetermined value. Initialization.

Wrong. This i, if it has an automatic storage, is not initialized.
Accessing it for anything else then writing (assigment or initialization) it
(well, reading it in any way) is undefined behavior.

--
Attila aka WW
Jul 19 '05 #26


Attila Feher wrote:

Karl Heinz Buchegger wrote:
Ying Yang wrote:


int i; //declared but not initialised
wrong. initialized to an undetermined value. Initialization.


Wrong.


OK.
(it was just a wild guess, apologies for that).

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #27
On Mon, 15 Sep 2003 20:41:24 +0930, "Ying Yang" <Yi******@hotmail.com>
wrote:
Ying Yang wrote:
>
>
> int i; //declared but not initialised


wrong. initialized to an undetermined value. Initialization.


disagree.

Initialization of an object or primitive means to give a determined value to
them for the first time.


Your "definition" of initialization is at odds with the C++ standard:

"1 When no initializer is specified for an object of (possibly
cv*qualified) class type (or array thereof), or the
initializer has the form (), the object is initialized as specified in
8.5. [Note: if the class is a non*POD, it is
default*initialized. ]"

Here's the bit in 8.5:
"9 If no initializer is specified for an object, and the object is of
(possibly cv*qualified) non*POD class type (or array thereof), the
object shall be default*initialized; if the object is of
const*qualified type, the underlying class type shall have a
user*declared default constructor. Otherwise, if no initializer is
specified for an object, the object and its subobjects, if any, have
an indeterminate initial value;"

In other words, if you don't explicitly initialize an int (which is a
POD type), it is initialized with an indeterminate initial value.

Tom
Jul 19 '05 #28
Karl Heinz Buchegger wrote:
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.


I was not clear. Of course it can only be assigned later on. Except of
course if someone is "clever enough" (remember! we talk about an int, POD)
and call placement new on its address. It would be an initialization,
although a pretty questionable one. :-)

--
Attila aka WW
Jul 19 '05 #29
On 14 Sep 2003 19:07:41 -0700, sb******@cs.uic.edu (Shane Beasley)
wrote:
Kevin Goodsell <us*********************@neverbox.com> wrote in message news:<dw*****************@newsread4.news.pas.earth link.net>...
Please show me where in the standard this definition is given.


As previously quoted, 4.1/1 clearly states that an lvalue may not be
used as an rvalue unless it was previously initialized. Apparently,

int n;
n = 0;

qualifies as initialization for these purposes. But it's not done via
direct- or copy-initialization syntax in the declaration of n; rather,
it's done via an assignment expression, so called because it performs
assignment.


That is a defect in the standard. It should say "indeterminate value":

http://std.dkuug.dk/jtc1/sc22/wg21/d...ctive.html#240

The intent of the standard is clear: initialization and assignment are
not ever meant to mean the same thing.

Tom
Jul 19 '05 #30
On Mon, 15 Sep 2003 14:14:13 +0300, "Attila Feher"
<at**********@lmf.ericsson.se> wrote:
Karl Heinz Buchegger wrote:
Ying Yang wrote:


int i; //declared but not initialised


wrong. initialized to an undetermined value. Initialization.

Wrong. This i, if it has an automatic storage, is not initialized.
Accessing it for anything else then writing (assigment or initialization) it
(well, reading it in any way) is undefined behavior.


The lvalue to rvalue conversion is undefined for indeterminate values
(use of the term "initialized" has been recognized as a defect in the
standard).

According to other parts of the standard (see my other posts), the
above does count as initialization to an indeterminate value.

Tom
Jul 19 '05 #31
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:3F***************@gascad.at...


Attila Feher wrote:

Karl Heinz Buchegger wrote:
Ying Yang wrote:
>
>
> int i; //declared but not initialised

wrong. initialized to an undetermined value. Initialization.
Wrong.


OK.
(it was just a wild guess, apologies for that).

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? (Or does it have to be
initialized in the declaration statement?)
Assigning the initial value of a variable (even const, called "final") is
allow in (for example) Java. They appear to keep track of a variable's state
as "uninitialized" and define the assigning of a value during construction
as initialization. Does C++ do this? If it did, then calling a constructor
as part of an initialization list is perfectly valid; and I think it is!
--
Gary
Jul 19 '05 #32
On Fri, 12 Sep 2003 16:34:29 -0400, "jeffc" <no****@nowhere.com>
wrote:

"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:bj********@dispatch.concentric.net...
Erik wrote:
...
>>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) {}
>


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?


How do you think?

MyClass(int a): i(someFunction(a))
{
}

someFunction might be a member (static or otherwise), or a namespace
scope function.

Tom
Jul 19 '05 #33
tom_usenet wrote:
specified for an object, the object and its subobjects, if any, have
an indeterminate initial value;"

In other words, if you don't explicitly initialize an int (which is a
POD type), it is initialized with an indeterminate initial value.


No "in other words". They will have an "indeterminate initial value". They
are *not* initialized. Furthermore (let's not force me to look up the
paragraph) accessing such an uninitialized variable is undefined behavior.
(BTW it is in 4.1 paragraph 1)

--
Attila aka WW
Jul 19 '05 #34
tom_usenet wrote:
On Mon, 15 Sep 2003 14:14:13 +0300, "Attila Feher"
<at**********@lmf.ericsson.se> wrote:
Karl Heinz Buchegger wrote:
Ying Yang wrote:
int i; //declared but not initialised

wrong. initialized to an undetermined value. Initialization.

Wrong. This i, if it has an automatic storage, is not initialized.
Accessing it for anything else then writing (assigment or
initialization) it (well, reading it in any way) is undefined
behavior.


The lvalue to rvalue conversion is undefined for indeterminate values
(use of the term "initialized" has been recognized as a defect in the
standard).

According to other parts of the standard (see my other posts), the
above does count as initialization to an indeterminate value.


If that is what the standard is being changed to, then it is pretty silly.
Initialization is an _action_ being taken. So we say (for automatic/member
PODs): if they are are not initialized then we call this initialization
which never happened as initialization to an indetermined value. Great. It
goes to the deepness of the quantum physics. Furthermore: it has a value,
but that value cannot be read... That suggests me that it is *not*
initialized. It has an indetermined, and non-determinable value. Like the
female-mind vs. male-mind. ;-)

--
Attila aka WW
Jul 19 '05 #35
<Shane Beasley>
it doesn't matter what your opinion (or mine) is; neither of us will
learn anything about C++ that we didn't already know before this
thread </>

I do learn from this thread. There are always people lurking. And,
for once, it's on topic!
"Arguing on the Internet is like competing in the Special Olympics...
Even if you win, you're still retarded."


:-)

-X
Jul 19 '05 #36
On Mon, 15 Sep 2003 15:29:36 +0300, "Attila Feher"
<at**********@lmf.ericsson.se> wrote:
tom_usenet wrote:
specified for an object, the object and its subobjects, if any, have
an indeterminate initial value;"

In other words, if you don't explicitly initialize an int (which is a
POD type), it is initialized with an indeterminate initial value.


No "in other words". They will have an "indeterminate initial value". They
are *not* initialized. Furthermore (let's not force me to look up the
paragraph) accessing such an uninitialized variable is undefined behavior.
(BTW it is in 4.1 paragraph 1)


You snipped these words from my post (reproduced in paraphase):

"When no initializer is specified for an object of class type the
object is initialized as specified in 8.5."

Yes, when you don't give an initializer, it is still initialized.
"Initializer" and "Initialization" are different things. Even if you
don't use an initializer, initialization still takes place.

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)
int* q = p; //error, lvalue-to-rvalue conversion

Tom
Jul 19 '05 #37
On Mon, 15 Sep 2003 15:35:09 +0300, "Attila Feher"
<at**********@lmf.ericsson.se> wrote:
If that is what the standard is being changed to, then it is pretty silly.
Initialization is an _action_ being taken. So we say (for automatic/member
PODs): if they are are not initialized then we call this initialization
which never happened as initialization to an indetermined value. Great. It
goes to the deepness of the quantum physics. Furthermore: it has a value,
but that value cannot be read... That suggests me that it is *not*
initialized. It has an indetermined, and non-determinable value. Like the
female-mind vs. male-mind. ;-)


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."

"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.

Tom
Jul 19 '05 #38
<tom_usenet>
If you choose your words carefully it makes more sense


I am not very into this business of initialization (hard to type)
and assignment, so I try to understand it in a metaphore. The
magician with the White rabbit in the hat. First, there is no hat.
It is flat, doesn't need space. Then, the magician pops up the
hat. It takes up space and provides space. But it is 'empty'.
Is it? Is there a rabbit in the hat?

1. Yes, the rabbit was nicely folded flat in the hat.
2. No, the magician is about to put the rabbit in the hat.

For assignment, putting another rabbit in the hat, we must
visualize a flapdoor at the top of the hat. Is a rabbit POD or
is that not the question?

-X
Jul 19 '05 #39
Excuse me, I must add a third possibility (and a fourth)
I am not very into this business of initialization (hard to type)
and assignment, so I try to understand it in a metaphore. The
magician with the White Rabbit in the hat. First, there is no hat.
It is flat, doesn't need space. Then, the magician pops up the
hat. It takes up space and provides space. But it is 'empty'.
Is it? Is there a rabbit in the hat?

1. Yes, the rabbit was nicely folded flat in the hat.
2. No, the magician is about to put the rabbit in the hat.
3.. No, but the rabbit will jump in by itself
4. The Lovely Lady will put the rabbit in the hat

For assignment, putting another rabbit in the hat, we must
visualize a flapdoor at the top of the hat. Is a rabbit POD or
is that not the question?

-X


Jul 19 '05 #40
tom_usenet wrote:
[SNIP]
Yes, when you don't give an initializer, it is still initialized.
"Initializer" 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 "uninitialized" 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******@hotmail.com> wrote in message news:3f********@news.iprimus.com.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.
"Initializer" and "Initialization" are different things. Even if you
don't use an initializer, initialization still takes place.
Initialization 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*statement 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*list 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, "initialized" means "initialized by the compiler/runtime",
whereas the "uninitialized" 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 "inderminate 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."
Initialization == 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*******@axter.com> wrote in message
news:c1*************************@posting.google.co m...
"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.newshosting.co m...

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

news:3f********@news1.prserv.net...

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.newshosting.co m...

"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 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.newshosting.c om...

"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
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
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...
11
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,...
3
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...
13
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....
16
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...
14
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...
2
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);...
13
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
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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.