Overloading the () Operator?

I'd like an instance of my struct to be created as such:
 
Timer() 

as opposed to
 
Timer foo;


My struct is below.

1
2
3
4
5
6
7
  struct Timer {
        std::chrono::system_clock::time_point _startTime = std::chrono::system_clock::now();
        ~Timer() {
                std::chrono::system_clock::time_point _endTime = std::chrono::system_clock::now();
                std::cout << "That took: " << std::chrono::duration_cast<std::chrono::milliseconds>(_endTime - _startTime).count() << " seconds" << std::endl;
        }
};


Do I need to overload the () operator? If so (or if not), how do I go about achieving my desired results?
It works pretty fine as it is to me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <chrono>
#include <iostream>


struct Timer {
    std::chrono::system_clock::time_point m_startTime {
        std::chrono::system_clock::now()
    };

    Timer() = default;

    ~Timer()
    {
        std::chrono::system_clock::time_point m_endTime {
            std::chrono::system_clock::now()
        };
        std::cout << "That took: "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(
                        m_endTime - m_startTime
                      ).count()
                  << " seconds.\n";
    }
};


int main ()
{
    Timer();
}


That took: 0 seconds.


What’s your error?
Hmm... Really weird. It didn't work in my application but it's working the way you showed me.
It's probably worth mentioning: The rule in C++ is that if something can be a function declaration, it is one.

The () operator isn't being overloaded here.
If you were to write Timer timer(); the issue is that this looks like a function declaration to the compiler (a function that takes in no arguments and returns a Timer) and therefore it is one. The solution here is that no-arg constructors (when used on a named object) should not use parentheses.

This is actually kinda nice, because it lets you do
Timer timer; just like int a;

However, in the case of temporaries, you can call Timer(); like it was called in the previous example, because there is no ambiguity as to whether or not it is a function declaration.

This also leads to issues like "the most vexing parse".
https://en.wikipedia.org/wiki/Most_vexing_parse
Registered users can post here. Sign in or register to post.