initialization vs assignment

  • Thread starter Charles Stapleton
  • Start date
C

Charles Stapleton

Given the folowing class

class Ctest{
public:
Ctest( int i, int j) :a(i) { b = j; }
private:
int a, b;
}

When creating an object of type Ctest, what advantage is there to setting
the member variables a and b using initialization, :a(i), as opposed to
using assignment, b = j.

-charles
 
V

Victor Bazarov

Charles Stapleton said:
Given the folowing class

class Ctest{
public:
Ctest( int i, int j) :a(i) { b = j; }
private:
int a, b;
}

When creating an object of type Ctest, what advantage is there to setting
the member variables a and b using initialization, :a(i), as opposed to
using assignment, b = j.

This is answered in the FAQ Lite (you can find it if you follow the
link http://www.parashift.com/c++-faq-lite/). Please read the FAQ
before posting.

Victor
 
P

Pete

Charles said:
Given the folowing class

class Ctest{
public:
Ctest( int i, int j) :a(i) { b = j; }
private:
int a, b;
}

When creating an object of type Ctest, what advantage is there to
setting the member variables a and b using initialization, :a(i), as
opposed to using assignment, b = j.

-charles

IMHO, nothing, but when you have a variable of a class with no default
constructor, initialization is required.

- Pete
 
L

Leor Zolman

Given the folowing class

class Ctest{
public:
Ctest( int i, int j) :a(i) { b = j; }
private:
int a, b;
}

When creating an object of type Ctest, what advantage is there to setting
the member variables a and b using initialization, :a(i), as opposed to
using assignment, b = j.

For non-const primitive types and references (though there are some good
reasons to avoid const members or refs as data members), the only advantage
is stylistic. If you happen to have a /mixture/ of primitive and class-type
data members (along with base classes, perhaps), then all the
initializations can be shown in the same place and in a uniform style.

For any type with constructors, though, omitting the member (or base)
initialization forces invocation of that class's default constructor before
the body of the constructor is entered. If you then do an assignment in the
body of your constructor (assuming assignment is even supported for that
type), you'll be doing "extra work". If there's no default constructor, it
won't compile (probably the better scenario, since you find out sooner that
you've got some kind of a problem).
-leor
 
A

Alf P. Steinbach

* Leor Zolman said:
For non-const primitive types and references (though there are some good
reasons to avoid const members or refs as data members), the only advantage
is stylistic. If you happen to have a /mixture/ of primitive and class-type
data members (along with base classes, perhaps), then all the
initializations can be shown in the same place and in a uniform style.

For any type with constructors, though, omitting the member (or base)
initialization forces invocation of that class's default constructor before
the body of the constructor is entered. If you then do an assignment in the
body of your constructor (assuming assignment is even supported for that
type), you'll be doing "extra work". If there's no default constructor, it
won't compile (probably the better scenario, since you find out sooner that
you've got some kind of a problem).

For answers like these I think it's a good idea to refer to the FAQ.

FAQ: <url: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6>.

Unfortunately the FAQ does not mention the single most common "good" reason
to use assignment, namely, presence of initialization order dependencies.
Which should be designed away if possible, but that is sometimes impractical.
As a rule, if assignment is used instead of initialization list then either
there is an initialization order dependency or a newbie or both.
 
A

Alf P. Steinbach

* "Steven T. Hatton said:
It seems to me 'Please read the FAQ before posting' could be taken as
'Please RTFFAQ'.

Just spell it out: Read The Fucking Manual.

With prudish & easily offended Americans (who, without noticing any of it,
offend all others not by their choice of words but by their actions) all over
the net, however, it is perhaps best not asserted in that form.

It's a mystery to me how MIT could set up the RTFM site in the first place,
but then MIT has not only the best & brightest of the US population, but also
many bright people from the rest of the world. I am quite sure that in
current Norway, striving to be more American than the Americans, something
like the RTFM could never have been set up. But then we no longer have any
technical educational institutions left in Norway -- the miniature MIT
called NTH was, a few years ago, subsumed by a humanities oriented university.
 
V

Victor Bazarov

Steven T. Hatton said:
It seems to me 'Please read the FAQ before posting' could be taken as
'Please RTFFAQ'.

It could just as well be taken at its face value. What's your F point?
 
S

Steven T. Hatton

Alf said:
Just spell it out: Read The Fucking Manual.

With prudish & easily offended Americans (who, without noticing any of it,
offend all others not by their choice of words but by their actions) all
over the net, however, it is perhaps best not asserted in that form.

It's a mystery to me how MIT could set up the RTFM site in the first
place, but then MIT has not only the best & brightest of the US
population, but also
many bright people from the rest of the world. I am quite sure that in
current Norway, striving to be more American than the Americans, something
like the RTFM could never have been set up. But then we no longer have
any
technical educational institutions left in Norway -- the miniature MIT
called NTH was, a few years ago, subsumed by a humanities oriented
university.

It's not the idea of pointing people to the FAQ that I was addressing. It
was the confrontational undercurrent that seems to lie just below the
surface. Say the wrong thing on the newsgroup and the next thing you know,
you'll have someone going berserk and using profanity in some kind of flame
attacking not only you, but your country, and who knows what else.

Sorry if I don't follow suit by attacking your country. AFAIK, there are
many good people in Norway whom I don't wish to offend.

But the FAQ, does address this issue. Please take a look at the FAQ before
replying. I believe you might find the discussion enlightening.
 
A

Alf P. Steinbach

* "Steven T. Hatton said:
It's not the idea of pointing people to the FAQ that I was addressing. It
was the confrontational undercurrent that seems to lie just below the
surface. Say the wrong thing on the newsgroup and the next thing you know,
you'll have someone going berserk and using profanity in some kind of flame
attacking not only you, but your country, and who knows what else.

Hah, one should never needlessly limit an attack to person and country, as I
am sure your mother told you.

Sorry if I don't follow suit by attacking your country. AFAIK, there are
many good people in Norway whom I don't wish to offend.

Yada yada yada, "AFAIK there are many good negroes, jews, japs, frogs, etc.,
and one of my best friends is a lesbian". Actually there are. One of the
nice things about Norway is the humanitarian outlook (it's nice in general,
but as commented earlier not so good with respect to technical education).
E.g. we were early (1981) with having a female prime minister (Gro Harlem
Brundtland, <url: http://tinyurl.com/26x63>); then a female and lesbian
minister of justice (Anne Holt, who now mainly writes detective novels, <url:
http://tinyurl.com/34uby>, <url: http://tinyurl.com/yuqcc>), and currently a
male homosexual minister of economy (Per-Kristian Foss, <url:
http://tinyurl.com/3fsdm>) with a priest (Kjell Magne Bondevik, <url:
http://tinyurl.com/2azkv>) as prime minister -- we're simply not bigots, we
don't have that in us, but look at the US... When is the first lesbian
president or even member of Congress expected in the US? Never, I think;
and to take but one little example from current political debate, note that
in Per-Kristian Foss' official CV (from the Norwegian government), referred
above, he lives in a registered partnership -- when is that in the US?

But the FAQ, does address this issue. Please take a look at the FAQ before
replying. I believe you might find the discussion enlightening.

RTFM on topicality.
 
S

Steven T. Hatton

Alf said:
RTFM on topicality.
I trust you can find a Norwegian translation of the Hávamál by starting
here: http://www.forn-sed.no/main/nynorsk/informasjon.htm

From the Old Norse:

9. Sá er sæll
er sjálfr of á
lof ok vit, meðan lifir;
því at ill ráð
hefr maðr oft þegit
annars brjóstum ór.

10. Byrði betri
berr-at maðr brautu at
en sé mannvit mikit;
auði betra
þykkir þat í ókunnum stað;
slíkt er válaðs vera.

11. Byrði betri
berr-at maðr brautu at
en sé mannvit mikit;
vegnest verra
vegr-a hann velli at
en sé ofdrykkja öls.

12. Er-a svá gótt
sem gótt kveða
öl alda sonum,
því at færa veit
er fleira drekkr
síns til geðs gumi.

13. Óminnishegri heitir
sá er yfir ölðrum þrumir;
hann stelr geði guma;
þess fugls fjöðrum
ek fjötraðr vark
í garði Gunnlaðar.
 
A

Alf P. Steinbach

* "Steven T. Hatton said:
I trust you can find a Norwegian translation of the Hávamál

The English translation is actually more understandable.

Have you considered verses 1 through 8, not just 9 through 13? ;-)

Seriously, please don't more times suggest that the ordinary and polite
way to steer someone to the FAQ -- as Victor did -- is equivalent to
RTFFAQ. What you did there was to break two rules for visitors to the
house. Hinting (it seemed like) about Victor's motives, like "so you
really meant [bad thing]", and second, like "your customs are ungood".

Now I've tried both humor, low-intensity flaming and simple explanation.

I should perhaps have tried the last first, but done is done.


Cheers,

- Alf
 
A

Alf P. Steinbach

PS: My information about the US Congress turned out to be out of date.
It actually had Tammy Baldwin in 1998. So my guess was partially
incorrect.
 
S

Steven T. Hatton

Alf said:
The English translation is actually more understandable.

They all seem lacking to me. I prefer the Old Norse.
Have you considered verses 1 through 8, not just 9 through 13? ;-)

Certainly, but they didn't seem as apropos.
Seriously, please don't more times suggest that the ordinary and polite
way to steer someone to the FAQ -- as Victor did -- is equivalent to
RTFFAQ.

I didn't say it was equivalent. I said it might be taken that way.
What you did there was to break two rules for visitors to the
house. Hinting (it seemed like) about Victor's motives, like "so you
really meant [bad thing]", and second, like "your customs are ungood".

I still don't fully understand /why/ m_x(x) works in the following:

#include <iostream>

class A {
int m_x;
public:
A(int x):m_x(x){};
int getX(){return m_x; };
};

int main(int argc, char* argv[]) {
A a(5);
std::cout << a.getX() << std::endl;
}
Now I've tried both humor, low-intensity flaming and simple explanation.

I should perhaps have tried the last first, but done is done.


Cheers,

- Alf

What Gore really meant when he pointed to his work with the Internet was not
that he invented the Internet - which he never said - but that he did a lot
to popularize it, and disseminate information about the use of web browsers
to people in prominant and influential positions. I set up the systems he
use to do it.
 
A

Alf P. Steinbach

* "Steven T. Hatton said:
I still don't fully understand /why/ m_x(x) works in the following:

#include <iostream>

class A {
int m_x;
public:
A(int x):m_x(x){};
int getX(){return m_x; };
};

int main(int argc, char* argv[]) {
A a(5);
std::cout << a.getX() << std::endl;
}

I guess you mean why it should be preferred over assignment. In this
case, with 'int' type, and nothing else going on in the constructor, I
see no technical reason and no readability reason. But it's like
a car driver indicating which way he's about to drive at crossroads even
when there are no other cars in sight: the habit helps to do the Right
Thing in general, and perhaps there's someone waiting to cross the
street, just not very clearly in sight, making the decision to cross...

Btw., by declaring 'getX' as a 'const' member function it will be
possible to call it also on 'const' A-objects.

What Gore really meant when he pointed to his work with the Internet was not
that he invented the Internet - which he never said - but that he did a lot
to popularize it, and disseminate information about the use of web browsers
to people in prominant and influential positions. I set up the systems he
use to do it.

I'm not sure whether this is some subtle thing or a hint about off-topicality
or an effort to convince me that you are no dummy (I do know, at least if
earlier comments about implementing mathematical models is true), or boasting,
or what. But it doesn't seem very relevant. If it's simply "by the way I met
a famous person", well most of us have; e.g. I shook hands with Bill Clinton
last time he was in Oslo -- I was prevented from leaving the entrance to a
shop by security guards, then came Bill, and of course he had to shake hands
with a beautiful lady beside me, and another one, and then for consistency
with me too as the last person before the entrance to the shop. Later the
same week I met a famous (in Norway and Italy) Norwegian pop-star, Lene
Marlin, or at least I think I did, but being afraid that possibly it wasn't
her I didn't dare to say hello. Barring a major fault in the pop-star
recognition circuits, however, I think I met two very famous persons in the
span of just one week, and actually shook hands with one of them!
 
S

Steven T. Hatton

I guess you mean why it should be preferred over assignment.

I don't know what formal language principle underlies the mechanism. That's
why I'm sitting here with the Standard and a highlighter. Yes, it's in
hardcopy printed using psutils. I'm not using the highlighter on the
electronic version in PDF! :)
Btw., by declaring 'getX' as a 'const' member function it will be
possible to call it also on 'const' A-objects.

Thanks for the pointer, I still have a lot to internalize.
I'm not sure whether this is some subtle thing

The point was I might be a bit new to this particular newsgroup, but I'm not
new to usenet. At some point I'm no longer a newbie in this newsgroup.
For me to comment on how others are treated is not necessarily improper for
a guest (the Hávamál is the song of a wandering singer), but I think I've
been around long enough to not qualify as a newbie.
But it doesn't seem very relevant. If it's simply "by the way I
met a famous person", well most of us have; e.g. I shook hands with Bill
Clinton
last time he was in Oslo -- I was prevented from leaving the entrance to
and then for consistency with me too as the last person before the

I hope you washed your hand with hot water and soap before touching
anything, especially your face, or other sensitive part of your body.
Later the
same week I met a famous (in Norway and Italy) Norwegian pop-star, Lene
Marlin, or at least I think I did, but being afraid that possibly it
wasn't
her I didn't dare to say hello. Barring a major fault in the pop-star
recognition circuits, however, I think I met two very famous persons in
the span of just one week, and actually shook hands with one of them!

I met Stephen Wolfram, and didn't even know it at the time. I never met
Gore, I just set up the systems. I'm far more pleased to have had a chance
to meet and interact with John A. Wheeler, than I would be to have met
Gore.

http://pupgg.princeton.edu/www/jh/announcements/wheeler_symposium.html
 
A

Alf P. Steinbach

* "Steven T. Hatton said:
I don't know what formal language principle underlies the mechanism. That's
why I'm sitting here with the Standard and a highlighter. Yes, it's in
hardcopy printed using psutils. I'm not using the highlighter on the
electronic version in PDF! :)

Again I'm not quite sure what you mean. But possibility 1: what you mean by
formal language mechanism is the C++ definition of initializer list. You'll
find that in section §12.6.2 of the Holy Standard. With the colon it's
called a ctor-initializer, and sans the colon it's a mem-initializer-list.

Possibility 2: what you mean by formal language mechanism is a language-
independent thing that §12.6.2 is the C++ language implementation of. Sorry,
can't help you there. Except that it's possible to find formal definitions
of just about anything just by looking and searching hard enough; and if one
does not exist it can always be produced.

Possibility 3: what you mean by formal language mechanism is what purpose
does it serve, when e.g. Java seems to do well without it? Well, one thing
that is different between Java and C++ is that a Java object of a type with
constructor can only be referred to by reference, whereas in C++ it can be
a local variable say (or directly occupy storage in another object, or
static storage). To ensure type safety -- that all member objects with
constructors have their constructors called -- the language design choice
is then between (A) not having automatic constructor calls but instead require
the equivalent of placement new for all subobjects, one can't just leave the
members as null-references as in Java, and (B) having automatic constructor
calls, in which case additional initialization in the constructor body will
be inefficient, and there is the problem of providing constructor arguments.
C++ uses solution (B), and solves the both inefficiency problem and the
argument passing problem with the constructor initializer lists mechanism.

In addition constructor initializer lists solve the problem of initializing
const members.

But an alternative to that could be not to design the language with const
members but with 'readonly' members which turn to 'readonly' state only
after the constructor has finished.

I met Stephen Wolfram, and didn't even know it at the time.

You would have been infected with cellular automata. But I rather liked
his program for displaying Sierpinski-like triangles. Since this is a C++
newsgroup, here's the Perl version, courtesy of Lars Christian Jensen:

perl -e 'for$a(0..63){for(0..$a){print($_&~$a?" ":"#")}print"\n"}'

John A. Wheeler

For some reason he reminds me of the book "wheelers" by Ian Stewart... ;-)
 
S

Steven T. Hatton

Alf said:
Again I'm not quite sure what you mean. But possibility 1: what you mean
by
formal language mechanism is the C++ definition of initializer list.
You'll
find that in section §12.6.2 of the Holy Standard. With the colon it's
called a ctor-initializer, and sans the colon it's a mem-initializer-list.

Thanks for the pointer. But that's not what has me puzzled.
Possibility 2: what you mean by formal language mechanism is a language-
independent thing that §12.6.2 is the C++ language implementation of.

I don't believe it's an implementation issue.
Sorry,
can't help you there. Except that it's possible to find formal
definitions of just about anything just by looking and searching hard
enough; and if one does not exist it can always be produced.

Nobody ever responded to my question about what else significant is on the
page of K&R in the Grammar where the function main() is specified. I
wonder why.
Possibility 3: what you mean by formal language mechanism is what purpose
does it serve, when e.g. Java seems to do well without it?
Nope.

Well, one
thing that is different between Java and C++ is that a Java object of a
type with constructor can only be referred to by reference, whereas in C++
it can be a local variable say (or directly occupy storage in another
object, or
static storage). To ensure type safety -- that all member objects with
constructors have their constructors called -- the language design
choice is then between (A) not having automatic constructor calls but
instead require the equivalent of placement new for all subobjects, one
can't just leave the members as null-references as in Java, and (B) having
automatic constructor calls, in which case additional initialization in
the constructor body will be inefficient, and there is the problem of
providing constructor arguments. C++ uses solution (B), and solves the
both inefficiency problem and the argument passing problem with the
constructor initializer lists mechanism.

I guess there are advantages to any of the approaches. Java is a very
regular language which may be a bit awkward at times, but it's also
straightforward. C++ reminds me of something Mithrandir might study. There
seems to be a lot of magic in it. Hard to master, hard to perceive, but
powerful when you do master it.


Here's the question. Where (how) does the Holy Standard specify that I can
do this:

int main(int argc, char* argv[]) {
int i(3); // <---<---
std::cout <<"i = " << i << std::endl;
}


You would have been infected with cellular automata. But I rather liked
his program for displaying Sierpinski-like triangles. Since this is a C++
newsgroup, here's the Perl version, courtesy of Lars Christian Jensen:

I don't know if I'm susceptible to fullblown Cellular Automata. I've done a
lot of fun stuff in Mathematica, but there is something fundamental I have
yet to grasp. It may be something it shares with Lisp, which I've never
mastered. I know it has to do with up-values. But I don't even want to
think about that right now.
perl -e 'for$a(0..63){for(0..$a){print($_&~$a?" ":"#")}print"\n"}'

And you suggested "UBC" was profane in C++ circles? ;-)
For some reason he reminds me of the book "wheelers" by Ian Stewart... ;-)

Don't know the book, but this will tell you more about Wheeler:
http://www.usd.edu/phys/courses/phys300/gallery/clark/wheeler.html
 

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

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top