Home > Enterprise >  Why is it required to add certain fields as a parameter to the constructor in C
Why is it required to add certain fields as a parameter to the constructor in C

Time:10-13

Probably a simple a question, but I haven't found anything yet. For the code below, the IDE complains about the field and suggests to "Add as parameter to the constructor".

#include <chrono>
class TestClass {
private:
    std::chrono::time_point start;
public:
    TestClass(){
        start = std::chrono::steady_clock::now();
    }
};

Question 1: What is wrong about the code?

Question 2: How is it possible to define a time_point as a field?

CodePudding user response:

Any fields not listed in the constructor's initializer list will be default initialized. So your code is equivalent to this.

TestClass() : start() {
  start = std::chrono::steady_clock::now();
}

For things like strings or vectors, this is harmless but silly. We default-construct an empty string or vector and then assign another one to it using operator=. But std::chrono::time_point doesn't have a default constructor, so you can't initialize it this way. Instead, place the argument to the constructor in the initializer list.

TestClass() : start(std::chrono::steady_clock::now()) {}

You should do this anyway, even if the type can be default constructed. It's more efficient and correct to initialize the value the first time, rather than letting default initialization happen and then assigning to it. But you must do this if there's no default constructor.

CodePudding user response:

std::chrono::time_point is a template class, meaning you can not instantiate it without giving the required template parameters. In this case that's the first template parameter Clock. I.e. you need to tell for which clock you want to store a time point.

You can fix that by adding your clock:

std::chrono::time_point<std::chrono::steady_clock> start;

But clocks also have a time_point type alias, so you write the shorter:

std::chrono::steady_clock::time_point start;
  • Related