Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a subclass of thread Class properly in C++(subclass of std::thread)

I am trying to create a class Parallel which is a subclass of std::thread,therefore my class is defined in Parallel.h,but the main method defined in separate file main.cpp in same project(in visual studio).When I create an instance of Parallel and execute join() function in main() method as below code segment: I am new to C++, here is the "Parallel.h"-

#include<thread>
using namespace std;
namespace Para{
class Parallel:thread
{
public:

    static void run(){

    }
    Parallel(void)
    {
    }

    virtual ~Parallel(void)
    {
    }

    inline static void start(Parallel* p){
                // (*p).join();
    }

    virtual void Parallel::start(thread& t){

    }
    static void parallelize(Parallel& p1,Parallel& p2){

    }
    inline virtual Parallel* operator=(thread* t){
        return  static_cast<Parallel*>(t);
    }
}

//in main.cpp

void main(){

    Parallel p;
    p.join();
    thread t(print);
     t.join();
     system("Pause");

}

Problem is how to define a proper subclass of a thread class having a overloaded constructor taking function name as a parameter,also when defined p.join() compiler given following errors in VS2012:

Error 2 error C2247: 'std::thread::join' not accessible because 'Para::Parallel' uses 'private' to inherit from 'std::thread' C:\Users\Gamer\Desktop\PROJECQ\VC++@OMAQ\CQ47\CQ47\main.cpp 11

3 IntelliSense: function "std::thread::join" (declared at line 209 of "H:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\thread") is inaccessible c:\Users\Gamer\Desktop\PROJECQ\VC++@OMAQ\CQ47\CQ47\main.cpp 11

like image 688
Buddhika Chaturanga Avatar asked Mar 23 '23 03:03

Buddhika Chaturanga


1 Answers

The error about "uses 'private' to inherit" when you try to call 'p.join()' is because you have written:

    class Parallel:thread

When you should have written:

    class Parallel : public thread

The default is private inheritance, which means all methods of the base class become private on the inheriting class. You have to specify that the inheritance should be public if you want them to be accessible.

like image 177
Sean Burton Avatar answered Mar 25 '23 12:03

Sean Burton