0

I have a hard time understanding the following code, can someone please elaborate.

struct WUpdate {
    explicit WUpdate(std::string id = "", std::string message = "")
        : id(std::move(id)), message(std::move(message)) {}
    explicit WUpdate(const UpgradeJob& job)
        : id(job.m.id), message(job.message) {}

    std::string id;
    std::string message;
};

I want to update the above struct to accept a new field as well (called time below) with default value -1. I have updated the code above as follows:

struct WUpdate {
    explicit WUpdate(std::string id = "", std::string message = "", int time = -1)
        : id(std::move(id)), message(std::move(message)) {}
    explicit WUpdate(const UpgradeJob& job)
        : id(job.m.id), message(job.message) {}

    std::string id;
    std::string message;
    int time{-1};
};

the code compiles but when running I can see that the value of time is always set to -1, regardless of what I try to initialise it with. I am also getting warning saying that warning: unused parameter ‘time’ pointing to the second line of updated code.

theAlse
  • 5,577
  • 11
  • 68
  • 110

1 Answers1

2

the code compiles but when running I can see that the value of time is always set to -1, regardless of what I try to initialise it with.

None of the explicit keyword or that default value thing you mentioned has anything to do with time being always set to -1. You simply forgot to initialize time in the constructor as follows:

struct WUpdate {
    explicit WUpdate(std::string id = "", std::string message = "", int time = -1)
        : id(std::move(id)), message(std::move(message)), 
          time(time) /* <- Here */
    { }

    // ...
};
Dean Seo
  • 5,486
  • 3
  • 30
  • 49