0
class Decoder    {
public:
    virtual void run() {}
    //...
}

Now, I have this derived class:

class NVDecoder : public Decoder
{
public:
    void run();

which is defined as this in the NVDecoder.cpp file

void NVDecoder::run()
{
//...
}

As the function void of Decoder is virtual, doing:

//Decoder decoder = new NVDecoder();
auto decoder = std::make_shared<NVDecoder>(NVDecoder::NALU,Decoder::H264);
decoder->run();

should call the NVDecoder's run function, not the Decoder's one. However, when I start a thread for a generic Decoder object, I need to do like this:

auto decoderThread = std::make_shared<std::thread>(&Decoder::run, decoder);

This calls the Decoder's run function, not the NVDecoder's one. I guess it's because I pass &Decoder::run. How do I start a thread that uses the NVDecoder's run function without passing &NVDecoder::run?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1
    Classic object slicing: `decoder` is a `Decoder`, not an `NVDecoder`: that one died just after initializing `decoder`. You need references to observe polymorphism, as in `Decoder &&decoder = NVDecoder();`. – Quentin Sep 02 '19 at 20:00
  • It shouldn't. Here 'Decoder decoder = NVDecoder();' you 've just get a slicing of the derived object. so run will be from base class. Try to use pointers. 'Decoder* decoder = new NVDecoder();' – Roout Sep 02 '19 at 20:03
  • @Roout actually it was supposed to be a shared pointer, I updated the example. – Guerlando OCs Sep 02 '19 at 20:08
  • @Roout in the case of a shared pointer, how sould I pass the object to the thread? – Guerlando OCs Sep 02 '19 at 20:09
  • Aditionally, why I can call the derived's function when using pointers but not when using object instances? – Guerlando OCs Sep 02 '19 at 20:22
  • @Guerlando OCs Because when you are using pointers to create object you do not perform copy operation on object itself. Consider example. Base base = Derived der; you create derived object first then you call copy constructor which by default will "cut off" all variables and fucntions that are not in Base class. So you end up with object that is of type Base but created from Derived. Using pointers: Base * base = new Derived (); you create pointer of type Base which points to object of type Derived (containing all infromation from Derived class) – NewMe Sep 02 '19 at 20:37

0 Answers0