473,385 Members | 1,531 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,385 software developers and data experts.

Initialization in a constructor

Now, in C++ you can do:

struct X
{
int ia;
int ib;
};

class CL
{
public:
X x1;
int a, b;

// you can do this
CL() : a(0), b(0)
{
}

// and you can do this
void DoSomething()
{
X xx = {0}; // it's equivalent to a memset(&xx, 0, sizeof(X));
}
};

Now... How can I zero x1 in the CL constructor?
And... Why the X xx = {0} works? It seems a strange syntax...

--- bye
Jul 22 '05 #1
5 1307
Massimiliano Alberti wrote:
Now, in C++ you can do:

struct X
{
int ia;
int ib;
};

class CL
{
public:
X x1;
int a, b;

// you can do this
CL() : a(0), b(0)
{
}

// and you can do this
void DoSomething()
{
X xx = {0}; // it's equivalent to a memset(&xx, 0, sizeof(X));
}
};

Now... How can I zero x1 in the CL constructor?


If you provide a default constructor for struct X:
struct X
{
int ia;
int ib;

X() : ia(0), ib(0) { ; }
};

Now when you declare an instance of struct X, it
will automatically initialize.
void DoSomething()
{
X xx; // Calls the constructor of struct X.
cout << "x.ia = " << x.ia << endl;
return;
}
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 22 '05 #2
Massimiliano Alberti wrote in news:SA**********************@news3.tin.it:
Now, in C++ you can do:

struct X
{
int ia;
int ib;
};

class CL
{
public:
X x1;
int a, b;

// you can do this
CL() : a(0), b(0)
Add the follwing:

, x1()
{
}

// and you can do this
void DoSomething()
{
X xx = {0}; // it's equivalent to a memset(&xx, 0, sizeof(X));
Not really see below
}
};

Now... How can I zero x1 in the CL constructor?
See above, though since x1 comes before a and b you may want to
put it before a(0). i.e. CL() : x1(), a(0), b(0) {}.

This causes value initialization, which in this case
initializes x1's members to 0.

Note: Don't be tempted to start writing:

void f()
{
X x(); /* Whoopse, its a function declaration!, though */
X xx = X(); /* is Ok. */
}
And... Why the X xx = {0} works? It seems a strange syntax...


Its a shortend form of an aggragate initializer:

X xx = { 1, 2 };

Will initialize xx's members to 1 and 2 respectivly, if you stop
before you've initialized all members the remainder are default
initialized, either there default constructor is called, or in
the case of inbults (int etc) they are initialized with 0.

Note that X xx = {}; will work just as well in this case.

HTH.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #3
> See above, though since x1 comes before a and b you may want to
put it before a(0). i.e. CL() : x1(), a(0), b(0) {}.

Why? Is it to help the optimizer? (the compiler will more easily see that
I'm zeroing a contigous area of memory and optimize it)

--- bye
Jul 22 '05 #4
Massimiliano Alberti wrote in
news:e%**********************@news3.tin.it:
See above, though since x1 comes before a and b you may want to
put it before a(0). i.e. CL() : x1(), a(0), b(0) {}.

Why? Is it to help the optimizer? (the compiler will more easily see
that I'm zeroing a contigous area of memory and optimize it)


No the compiler will intialize members in declaration order,
and some compilers (g++) will warn you that the order you specify
in the initializer list *isn't* the order in which the initialization
is done.

#include <iostream>
#include <ostream>
#include <iomanip>

struct X
{
int a, b;

X() : b( 10 ), a( b ) {}
};
int main()
{
using namespace std;
cerr << X().a << '\n';
}

Of the 5 comilers I tried this on only 1 printed 10, 2 (both versions
of g++) warned about the "order problem", 4 of the compilers I
consider to be "highly" Standard conforming (including the one that
printed 10).

It's certainly the case that you can't reorder the initialization
of base classes, but that doesn't apply here, so it may be that
the 1 compiler (CBuilderX (preview)) that printed 10 is correct (i.e.
Standard conforming (*)). But from a practical point of view, we
should put initializers in declaration order for consistant portable
results.

Note (*) If I ever *need* to do an out of order initialization I
might check the Standard, I currently don't care as 25% of compilers
isn't portable, Standard conforming or not.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #5
Massimiliano Alberti wrote:
...
X xx = {0}; // it's equivalent to a memset(&xx, 0, sizeof(X));
...


No, it is not.

The only types in C++ which can be predictably zeroed by using
'memset(.., 0, ..)' are 'char', 'signed char' and 'unsigned char' (and
aggregates built from these types). If you steamroll over an object of
any other type with 'memset(.., 0, ..)' you'll simply end up with an
object filled with "all-zeroes" bit-pattern, which does not necessarily
represents a "zero" value of that type. Moreover, it will not
necessarily be a valid object of that type at all.

In your case you are trying to zero-initialize 'int' objects with
'memset(.., 0, ..)'. This is not guaranteed to work in C++, even though
in most cases it works in practice.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #6

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

Similar topics

6
by: Alexander Stippler | last post by:
Hi, I wonder about the behaviour of como and icc on some very simple program. I thought initializing members of classes, which are of class type, would be 'direct initialized' (as the standard...
1
by: Jacek Dziedzic | last post by:
Hi! A) Why isn't it possible to set a member of the BASE class in an initialization list of a DERIVED class constructor (except for 'calling' the base constructor from there, of course)? I even...
17
by: Thomas Lorenz | last post by:
Hello, I'm a little confused about object initialization. According to Stroustrup (The C++ Programming Language, Special Edition, Section 10.2.3) constructor arguments should be supplied in one...
10
by: JKop | last post by:
What's the difference between them? Take the following: #include <iostream> struct Blah { int k;
6
by: anongroupaccount | last post by:
class CustomType { public: CustomType(){_i = 0;} CustomType(int i) : _i(i) {} private: int _i; }; class MyClass
10
by: utab | last post by:
Dear all, Can somebody direct me to some resources on the subject or explain the details in brief? I checked the FAQ but could not find or maybe missed. Regards,
8
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it....
23
by: Jess | last post by:
Hello, I understand the default-initialization happens if we don't initialize an object explicitly. I think for an object of a class type, the value is determined by the constructor, and for...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
11
by: subramanian100in | last post by:
Suppose we have a class named Test. Test obj; // assuming default ctor is available Test direct_init(obj); // direct initialization happens here Test copy_init = obj; // copy initialization...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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?

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.