0
#include <iostream>
#include <thread>
class DisplayThread
{
public:
    void operator()()     
    {
        for(int i = 0; i < 10000; i++)
            std::cout<<"Display Thread Executing"<<std::endl;
    }
};
 
int main()  
{
   //line 1:
    std::thread threadObj( (DisplayThread()) );
    for(int i = 0; i < 10000; i++)
        std::cout<<"Display From Main Thread "<<std::endl;
    std::cout<<"Waiting For Thread to complete"<<std::endl;
    threadObj.join();
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}
    

In line 1: if i use like "threadObj(DisplayThread())", It gives an error saying no class type.

Could someone tell me why functor while passing to thread constructor has to be inside"()" braces?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
StraightCirle
  • 182
  • 2
  • 12
  • 1
    `std::thread threadObj(testObj());` calls the `DisplayThread::operator()()`. I think you want the thread to call it instead. – JFMR Sep 04 '20 at 09:16

1 Answers1

3

Congratulations... of sorts: You have fallen victim to the C++ phenomenon known as the Most Vexing Parse: Basically, a tendency of the compiler to interpret your statements as function declarations. You are not at fault - it's the result of ambiguity in the language which happens to be resolved in a somewhat unintuitive way.

The error you get when you remove the parentheses around DisplayThread() is:

<source>: In function 'int main()':

<source>:20:15: error: request for member 'join' in 'threadObj', which is of 
non-class type 'std::thread(DisplayThread (*)())'
   20 |     threadObj.join();
      |               ^~~~

The compiler thinks threadObj is a function, which takes a function pointer and returns an std::thread!

This is resolved if you use curly-braces for no-argument construction, like so:

std::thread threadObj{ DisplayThread{} };
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • thanks for the answer. Was not aware of this phenomenon. Learnt a new thing today. – StraightCirle Sep 04 '20 at 09:57
  • @StraightCirle: Of course you weren't aware of it, that's why it's [vexing](https://www.thefreedictionary.com/vexing) to everyone at first... – einpoklum Sep 04 '20 at 11:08