1

To my understanding of c++ I always thought I should be able to do the following and call the default constructor in this manner:

#include <iostream>

void do_some_work() {
    std::cout << "Doing some work" << std::endl;
}

void do_something_else() {
    std::cout << "Doing something else." << std::endl;
}


class background_task
{
public:
    background_task()
    {
        std::cout << "Calling the constructor!" << std::endl;
    }
};

int main()
{
    background_task f();
    getchar();
    return 0;
}

After executing the program above I see that the default constructor I have provided and instead it is only blank and no message gets outputted on the screen. I know that I am supposed to call it in this way:

background_task f;

And when I do it calls normally my default constructor and I see the printing in the screen. I wonder why in the first case it doesn't appear anything, is it not legal that statement if not why doesn't the crash happen?

Erindy
  • 155
  • 11

1 Answers1

3

This looks like a case of the most vexing parse. Replace background_task f() with background_task f{} to ensure you're declaring a variable instead of a function.

Joshua Ryan
  • 628
  • 5
  • 12
  • Sorry, my bad. I would define it as `background_task f;` because with small fonts the difference between braces and parens is difficult for me to spot. –  Feb 23 '19 at 19:30
  • It's nice to use uniform initialization everywhere so that you don't accidentally forget to initialize a struct that doesn't have a user defined constructor. – Joshua Ryan Feb 23 '19 at 19:32
  • That may be true, but I personally don't find the syntax natural or readable. But we are obviously stuck with it. –  Feb 23 '19 at 19:33
  • 1
    @JoshuaRyan Thanks for the clarification, I totally missed that, I had read so much about most vexing parse and wondering why is it a problem, now I see but still seeing no error looked a bit weird. I know that the background_task f; is the way to go I was just curious about the dubious behavior. – Erindy Feb 23 '19 at 19:35