Search code examples
c++classoopscopectime

How to deal with ctime includes within the scope of a class in CPP?


I want to use <ctime> inside the scope of a class in C++. However, whenever I try to compile the following class, I get the error:

error: 'time' cannot be used as a function
      time_t now = time(0);

I think it may be something related to the fact that I am trying to call that function inside of the Session class, because I have managed to call the time() function inside the main() function.

What am I doing wrong?

Session.h

#ifndef _SESSION_H_
#define _SESSION_H_
#include <string>
#include <ctime>

class Session
{
private:
  std::string language;
  time_t date;
  time_t time;

public:
  Session(std::string language, time_t date = NULL, time_t time = NULL);
  ~Session();
};
#endif

Session.cpp

#include <ctime>
#include "Session.h"

Session::Session(std::string language, time_t date, time_t time) : language{language}, date{date}, time{time}
{
  if (date == NULL)
  {
    time_t now = time(0);
    tm *ltm = localtime(&now);
  }
}

Session::~Session() {}

Solution

  • You declared a constructor parameter with the same name time as the function name:

    Session::Session(std::string language, time_t date, time_t time)
                                                               ^
    

    Within the constructor block scope, the parameter hides the function with the same name (and also the data member with the same name declared in the class definition).

    So, use the qualified name for the function:

    time_t now = ::time(0);
    

    To access the data member, use an expression with the pointer this, like this->time.