Search code examples
c++classc++-chrono

Why is it required to add certain fields as a parameter to the constructor in C++


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?


Solution

  • 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;