VansFannel
VansFannel

Reputation: 45921

Default value in struct field when instance it

I've just started to learn C++.

I have this struct:

struct dateTime
{
    int sec;
    int min;
    int hour;
    int day;
    int mon;
    int year;
    bool daylightSaving;
    char timeZone;
};

And I need to set daylightSaving to false by default.

How can I do it? Maybe I have to use a class instead of a struct.

Upvotes: 2

Views: 51

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

You can write for example

struct dateTime
{
    int sec;
    int min;
    int hour;
    int day;
    int mon;
    int year;
    bool daylightSaving = false;
    char timeZone;
};

Upvotes: 3

Cyborg-X1
Cyborg-X1

Reputation: 373

So you say in C++, what about having a default constructor initializing all values?

struct dateTime
{
 dateTime()
 : sec(0)
 , min(0)
 , hour(0)
 , day(0)
 , mon(0)
 , year(0)
 , daylightSaving(false)
 , timeZone('a') //Are you sure you just want one character? time zones have multiple... UTC GMT ...
 {}

...
}

You can use a class instead, but the difference is only that all values are private by default. So you need

class ...
{
   public:
   ...
}

to have the same behavior as with the struct.

Upvotes: 1

Related Questions