473,583 Members | 3,072 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inititialing list/vector inside a constructor

Hello Group,

I have a class

class Simple2 {
publica:
Simple2();
list<int> *l1;
list<int> l2;
};

I am writing the constructor

Simple2::Simple 2 {

// It is easy to initialize l1

l1 = new list<int>;

}

How do I initialize l2 data member? The same thing I would like to ask
for vector class, if
it is an object and not a pointer how do you initialize template
classes.

Thanks for your help.

Nagrik

May 11 '06 #1
8 1902
arun wrote:
I have a class

class Simple2 {
publica:
Simple2();
list<int> *l1;
list<int> l2;
};

I am writing the constructor

Simple2::Simple 2 {
Simple2::Simple 2() {

// It is easy to initialize l1

l1 = new list<int>;
That's not initialisation. It's assignment. Initialisation would be
in the initialiser list. Yours is empty.

}

How do I initialize l2 data member?
Why do you think you need to? It's default-initialised for you.
The same thing I would like to
ask for vector class, if
it is an object and not a pointer how do you initialize template
classes.


Put them in the constructor initialiser list. What book on C++ are you
reading that doesn't explain this extremely basic feature of the language?

Simple2::Simple 2() : l1(new list<int>), l2()
{
}

V
--
Please remove capital As from my address when replying by mail
May 11 '06 #2
arun wrote:
Hello Group,

I have a class

class Simple2 {
publica:
public:
Simple2();
list<int> *l1;
list<int> l2;
};

I am writing the constructor

Simple2::Simple 2 {

// It is easy to initialize l1
Then do so. Below, you're not initializing. You are assigning.
l1 = new list<int>;

}

How do I initialize l2 data member?
With what? If the answer is "nothing", you're done, since it is
automatically defaul-initialized. That's the glory of classes.
The same thing I would like to ask for vector class, if
it is an object and not a pointer how do you initialize template
classes.


It has nothing to do with it being a template instance. You initialize it
like any other class.

May 11 '06 #3

Victor Bazarov wrote:
arun wrote:
The same thing I would like to
ask for vector class, if
it is an object and not a pointer how do you initialize template
classes.


Put them in the constructor initialiser list. What book on C++ are you
reading that doesn't explain this extremely basic feature of the language?

Simple2::Simple 2() : l1(new list<int>), l2()
{
}


but of course you cannot initialise them with data in a way you would
expect thus:

class HasVector
{
vector <int > v;

public:

HasVector() : v( { 1, 2, 3, 4, 5 } ) // illegal
{
}
};

The workaround is to define the initialisation array in anonymous
namespace.

namespace {
const int vecInit[] = { 1, 2, 3, 4, 5 };
const size_t vecInitSize = sizeof( vecInit ) / sizeof( vecInit[0] );
}

HasVector::HasV ector()
: v( &vecInit[0], &vecInit[vecInitSize] )
{
}

May 11 '06 #4
Earl Purple wrote:
Victor Bazarov wrote:
arun wrote:
The same thing I would like to
ask for vector class, if
it is an object and not a pointer how do you initialize template
classes.
Put them in the constructor initialiser list. What book on C++ are
you reading that doesn't explain this extremely basic feature of the
language?

Simple2::Simple 2() : l1(new list<int>), l2()
{
}


but of course you cannot initialise them with data in a way you would
expect thus:

class HasVector
{
vector <int > v;

public:

HasVector() : v( { 1, 2, 3, 4, 5 } ) // illegal
{
}
};

The workaround is to define the initialisation array in anonymous
namespace.

namespace {
const int vecInit[] = { 1, 2, 3, 4, 5 };
const size_t vecInitSize = sizeof( vecInit ) / sizeof( vecInit[0] );
}

HasVector::HasV ector()
: v( &vecInit[0], &vecInit[vecInitSize] )


I think it was just recently discussed that '&array[itssize]' has UB.
What's wrong with writing simply

v(vecInit, vecInit + vecInitSize)

?
{
}


V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 11 '06 #5
Earl Purple wrote:
Victor Bazarov wrote:
arun wrote:
The same thing I would like to
ask for vector class, if
it is an object and not a pointer how do you initialize template
classes.


Put them in the constructor initialiser list. What book on C++ are you
reading that doesn't explain this extremely basic feature of the language?

Simple2::Simple 2() : l1(new list<int>), l2()
{
}


but of course you cannot initialise them with data in a way you would
expect thus:

class HasVector
{
vector <int > v;

public:

HasVector() : v( { 1, 2, 3, 4, 5 } ) // illegal
{
}
};

The workaround is to define the initialisation array in anonymous
namespace.

namespace {
const int vecInit[] = { 1, 2, 3, 4, 5 };
const size_t vecInitSize = sizeof( vecInit ) / sizeof( vecInit[0] );
}

HasVector::HasV ector()
: v( &vecInit[0], &vecInit[vecInitSize] )
{
}


Assuming you fix the undefined behavior, that's not *the* work-around
so much as *a* work-around. See this post for another option:

http://groups.google.com/group/comp....fe5982913d4414

Cheers! --M

May 11 '06 #6
Hello Group,

I asked this question because I read it, that if a class itself is a
data member in another class then it must
be instantiated explicitely. However, according to replies, which I
got on this post it appears that if
a class/template has a default constructor and it is a data member in
another class, then that default
constructor will be called regard less when you call the container
class constructor and you don't have
to do the following

B has a data member C then you don't have to do this explicitely

B() : C() //

and following will work fine.

B() {// code goes here }

If this is the case then why does not the compiler initializes
primitive data members like ints to 'zero'
values. When I don't explicitely initialize ints then their values
after the constructor is called is
definitely not int but some thing else.

Kindly explain this behaviour.

thanks.

arun

May 12 '06 #7
arun wrote:
[...] it appears that if
a class/template has a default constructor and it is a data member in
another class, then that default
constructor will be called regard less when you call the container
class constructor and you don't have
to do the following

B has a data member C then you don't have to do this explicitely

B() : C() //

and following will work fine.

B() {// code goes here }

If this is the case then why does not the compiler initializes
primitive data members like ints to 'zero'
values.
Because the language Standard says so.
When I don't explicitely initialize ints then their values
after the constructor is called is
definitely not int but some thing else.


Primitive data types are left uninitialised for optimization. If you
don't care for a member of a primitive type to be initialised to
anything, then the compiler is not the one to decide what to set it to.
Classes that do have constructors must have their constructors invoked.
That's just how class objects are created. Primitive types do not have
constructors and therefore don't need to be initialised to anything.
It's essentially the same behaviour that you'd get if you write

int i;

versus

someclass obj;

In the former case, 'i' is left uninitialised, whereas 'obj' is actually
_constructed_ by invoking the [default] constructor from 'someclass'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 12 '06 #8
arun wrote:
If this is the case then why does not the compiler initializes
primitive data members like ints to 'zero'
values. When I don't explicitely initialize ints then their values
after the constructor is called is
definitely not int but some thing else.


For compatibility with C structs, and not use different rules depending if
the int is a member of a struct compatible with C or not. You can read "The
design and evolution of C++", for example, for the history and reasoning of
that type of things.

--
Salu2

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
May 12 '06 #9

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

Similar topics

14
1589
by: Dennis | last post by:
Hi I have a little problem as stated above (haven't found any solution on the www). I have a list of objects (particles) where I have a member of a template vector (array1d from TNT). I initialise these members in the constructor, but when I write different vector values to different particles the values becomes the same. I have found...
1
2582
by: Michael Jasn | last post by:
I had a question about memory management. Please look at the two functions below. Can you answer the two questions in the comments below. Thanks so much. -Mike func1(std::vector<Point>& points) { points.clear(); // Is this the right way to deallocate
17
3341
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling this uovec at the moment (for Unit-Offset VECtor). I want the class to respond correctly to all usage of STL containers and algorithms so that it is...
12
1801
by: ypjofficial | last post by:
Hello all, I have encountered with following strange problem. I am coding in C++ and using VC++ 6 compiler. I have a class strvector containing char * cstr as a private member and i have defined its destructor for releasing memory hold by cstr. In main i created a vector<strvector> and whenever i put a object of strvector inside this...
44
3841
by: Josh Mcfarlane | last post by:
Just out of curiosity: When would using std::list be more efficient / effective than using other containers such as vector, deque, etc? As far as I'm aware, list doesn't appear to be specialized for anything. Thanks, Josh McFarlane
18
3111
by: lchian | last post by:
Hi, I have a vector of class Foo. When I do a push_back(), I expect stl to call the default constructor I wrote for Foo. But instead, stl makes up its own default that is initialized with garbage. Is there a way to force stl to use MY default constructor?
6
2451
by: daveb | last post by:
I'm trying to write some code that calls the constructors of STL containers explicitly, and I can't get it to compile. A sample program is below. One compiler complains about the last two lines (the map constructor calls), saying that I'm trying to take the address of a constructor. Another compiler complains about all four of the last...
13
2451
by: Jeroen | last post by:
Hi all, I'm trying to implement a certain class but I have problems regarding the copy ctor. I'll try to explain this as good as possible and show what I tried thusfar. Because it's not about a certain code syntax but more a 'code architecture' thing , I'll use simple example classes (which are certainly not complete or working...) just to...
22
3601
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
0
7895
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...
0
7826
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...
0
8182
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6579
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...
1
5701
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...
0
3818
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...
0
3843
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1157
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...

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.