how to initialize the std::map

Z

zl2k

hi, there,

I have a class

class Foo{
public:
std::map<int, int> bar;
Foo();
}


Foo::Foo(): bar(){// am I doing right? I need to initialize an empty
bar
}

Thanks for help.

zl2k
 
R

red floyd

hi, there,

I have a class

class Foo{
public:
std::map<int, int> bar;
Foo();
}


Foo::Foo(): bar(){// am I doing right? I need to initialize an empty
bar
}

Yes, that is correct.

However, you don't even need to do that.

Foo::Foo() { }

Will call bar's constructor in the exact same manner.
 
A

Alf P. Steinbach /Usenet

* zl2k, on 11.10.2010 04:11:
hi, there,

I have a class

class Foo{
public:
std::map<int, int> bar;
Foo();
}


Foo::Foo(): bar(){// am I doing right? I need to initialize an empty bar
}

It's OK[1] but unnecessary -- std::map provides default initialization.


Cheers & hth.,

- Alf

Notes:
[1] Modulo the missing semicolon.
 
J

Jorgen Grahn

* zl2k, on 11.10.2010 04:11:
hi, there,

I have a class

class Foo{
public:
std::map<int, int> bar;
Foo();
}


Foo::Foo(): bar(){// am I doing right? I need to initialize an empty bar
}

It's OK[1] but unnecessary -- std::map provides default initialization.

It helps me to think of it this way: C++ makes it really, really hard
to accidentally create an uninitialized object[1]. With just the class
defined as above it compiles, and the only rational explanation is
that the std::map default constructor actually gets run!

/Jorgen
[1] Modulo malloc, memcpy and so on. You can come up with more examples,
I'm sure.
 

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
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top