class object initialisation

A

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
 
I

Ivan Vecerina

| 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,
 
J

jeffc

A said:
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;
 
E

Erik

Hi,
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
 
G

Gianni Mariani

Erik wrote:
....
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.
 
J

jeffc

Gianni Mariani said:
Erik wrote:
...

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?
 
J

jeffc

Erik said:
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.
 
R

Ron Natalie

jeffc said:
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.
 
R

Ron Natalie

jeffc said:
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?
 
K

Kevin Goodsell

Ying said:
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
 
S

Shane Beasley

(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
 
K

Kevin Goodsell

Shane said:
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
 
A

A

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

Kevin Goodsell

A said:
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
 
F

foo

jeffc said:
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;
}
 
F

foo

A said:
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.

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;
};
 
S

Shane Beasley

Kevin Goodsell said:
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
 
K

Kevin Goodsell

Shane said:
"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
 
S

Shane Beasley

Kevin Goodsell said:
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
 
K

Kevin Goodsell

Shane said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,585
Members
45,080
Latest member
mikkipirss

Latest Threads

Top