Oscar
Oscar

Reputation: 2345

Basic C++: How do I initialize a struct member of a class?

I've looked all over the place, but haven't found an answer to this.

I have a C++ class with these protected members:

 struct tm  _creationDate;
 struct tm  _expirationDate;
 struct tm  _lockDate;

I want to initialize them at instantiation time. If I put this in the constructor:

 _creationDate = {0};
 _expirationDate = {0};
 _lockDate = {0};

the compiler complains: "expected primary-expression before '{' token"

I also can't find a way to do it in a member-initializer list at the top of the constructor. How does one do this? Thanks!

FOLLOW-UP: Thanks for the replies, guys. You can't do it at the declaration; that's not allowed. So the only way appears to be memset or setting the members individually. I ended up writing a utility function to do just that.

Upvotes: 4

Views: 8062

Answers (4)

smerlin
smerlin

Reputation: 6566

Only way possible in C++03:

class foo
{
    tm _creationDate;
    public:
    foo()
    {
        tm tmp_tm = {0};
        _creationDate = tmp_tm;
    }
};

Note that this will initialize _creationDate with a copy of tmp_tm, thus invoking the (most likely autogenerated) copy-constructor. So for large structs, you should rather stick with your utility function, since that will not require copying the whole struct.

And by the way, names starting with an underscore (at global scope) are reserved for the standard library implementation. Names starting with an underscore followed by an uppercase letter are reserved everywhere. Technically the name _creationDate here is fine, since this is not at global scope, but I would still recommend to avoid using a leading underscore for names.

Upvotes: 1

stefanB
stefanB

Reputation: 79810

I think you can only initialize structure like that when you define it:

struct tm a = {0}; // works ok
struct tm b;
b = {0};           // error

One option is either to use "default" values

class a
{
    a() : t() {}
    struct tm t;
};

Or memset in constructor:

struct tm creationDate;
memset((void*)&creationDate, 0, sizeof(struct tm));

Upvotes: 1

w.donahue
w.donahue

Reputation: 10886

You can either do them at declaration like this

_creationDate = {0}; // set everything to 0's

or like this

_creationDate = { StructElement1, StructElement2, ..., StructElement n);

such as

_creationDate = { 0, false, 44.2);

Or in your constructor just call out each element in the structure and initialize such as...

_creationData.thing1 = 0;
_creationData.thing2 = false;
_creationData.thing3 = 66.3;

Upvotes: 2

Anycorn
Anycorn

Reputation: 51475

http://www.cprogramming.com/tutorial/initialization-lists-c++.html

class C {
    struct tm  _creationDate;
    struct tm  _expirationDate;
    struct tm  _lockDate;
    C() : _creationDate(), ... {}

Upvotes: 1

Related Questions