473,769 Members | 6,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class object initialisation

A
Hi,

I have always been taught to use an inialization list for initialising data
members of a class. I realize that initialsizing primitives and pointers use
an inialization list is exactly the same as an assignment, but for class
types it has a different effect - it calls the copy constructor.

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

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.516 / Virus Database: 313 - Release Date: 1/09/2003
Jul 19 '05
106 5601
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<7t******* ********@newsre ad3.news.pas.ea rthlink.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. "Uninitiali zed" is used to
mean "indetermin ate" 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.
Initializatio n 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(Sr c)+" 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(){Initializ e();}
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************ *********@never box.com> wrote in message news:<LR******* *********@newsr ead3.news.pas.e arthlink.net>.. .
Using an indeterminate lvalue is undefined. "Uninitiali zed" is used to
mean "indetermin ate" 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************ *********@never box.com> wrote in message news:<LR******* *********@newsr ead3.news.pas.e arthlink.net>.. .

Using an indeterminate lvalue is undefined. "Uninitiali zed" is used to
mean "indetermin ate" 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************ *********@never box.com> wrote in message news:<dw******* **********@news read4.news.pas. earthlink.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_initi alize, 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************ *********@never box.com> wrote in message news:<dw******* **********@news read4.news.pas. earthlink.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.

>>initializatio n - giving an object an initial value. Initialization
differs from assignment in that there is no previous value involved.
Initializatio n 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.re f_)
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_initi alize, 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 "Initialize rs" 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

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

Similar topics

1
3940
by: matro | last post by:
hi there, I have the following struct in my class: class CTbStDialog : public CDialog { public: int fooVar, fooVar2; ... //other foo variables...
8
2535
by: jose luis fernandez diaz | last post by:
Hi, I am reading Stroustrup's book 'C++ Programming Language'. In the 10.4.9 section (Nonlocal Store) he says: "A variable defined outside any function (that is global, namespace, and class static variables) is initializated (constructed) before main is invoked . . ." .. . .
11
2558
by: Neil Zanella | last post by:
Hello, When an "std::map<int, int> foobar;" statement appears in a C++ program followed by a statement of the form "foobar;" where nothing has ever been inserted at position 123 into map foobar, the C++ standard states that a new element is created at position 123 and is initialized to zero. That is, in this case, the pair (123, 0) is inserted into the map. I am interested in knowing what the standard says should happen in the
3
1282
by: deancoo | last post by:
I'm hoping this isn't too off topic, but I'm not sure if I've included some of my member functions in the right class. I needed to develop numerous functions to help define object A. These functions currently exist in the class definition for object A. The thing is, there is another object (B) who's job it is to call these functions when the app starts up, defining all possibilities for object A's, then allow future object A's to look up...
13
2075
by: Frederick Gotham | last post by:
I have just been reading 8.5 in the Standard, and am trying to make sense of the different kinds of initialisations. Up until now, I thought of an object as either NOT being initialised (i.e. containing garbage), or being default initialised (i.e. containing the default value for that type). Here are some examples of the former: struct MyStruct {
16
1477
by: silversurfer2025 | last post by:
Hello everyone, once again, I have a very basic problem in C++, which I was not able to solve (maybe because of my Java-Experience or just because it is always the small syntax-things which break my neck in C++)... I would like to have a static variable in class A and change its value from class B (they are not related to each other) For example:
14
2581
by: Jeroen | last post by:
Hi all, I've got a question about writing a library. Let me characterize that library by the following: * there is a class A which is available to the user * there is a class B that is used in severel 'underwater operations' * there is a list which stores objects of class B There are several issues I'm not sure about:
2
1902
by: .rhavin grobert | last post by:
i have (do try to have?) the following... & = breakpoints in debugger // ---------------------------------------------------------------- // cx.h class CX { public: CX(CX* pcx = NULL); virtual ~CX();
13
1653
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
9589
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.