I have a Base class with Derived1 and Derived2 derived classes and a Consumer class.
I want to create a vector of Base pointers with the two derived class objects to then pass to the consumer class so it can get derived class details using
pointervec.at(0).i
I've been stuck on this for ages and cannot get it to work. This is a simplified version of what I have. I'm concerned about the syntax around creating the vector, passing it to the thread and accessing different indexes.
#include<vector>
#include<thread>
#include<iostream>
using namespace std;
class Base
{
public:
Base() {};
void dosomething() {cout<<i<<endl;}
int i;
};
class Derived1 : public Base
{
public:
Derived1() {i = 5;}
};
class Derived2 : public Base
{
public:
Derived2() {i = 10;}
};
class Consumer
{
public:
Consumer();
void dostuff( vector<Base> &pointervec) {cout<<5<<endl;}
};
int main( int argc, char ** argv )
{
Derived1 derived1;
Derived2 derived2;
vector<Base*>pointervec;
pointervec.push_back(&derived1);
pointervec.push_back(&derived2);
std::thread t1(&Derived1::dosomething, &derived1);
std::thread t2(&Derived2::dosomething, &derived2);
std::thread t3(&Consumer::dostuff, ref(pointervec));
t1.join();
t2.join();
t3.join();
}
vector<Base>
is notvector<Base*>
– MikeCATvector<Base>&
type fordostuff()
, instead of thatvector<Base*>
that you're passing around? – πάντα ῥεῖpointervec
argument ofConsumer::dostuff
and compare with the type that you pass to the thread. – eerorikadoStuff()
needs avector<Base>
, and what cannot be satisfied in there usingvector<Base*>
there. – πάντα ῥεῖ