Reinier Hasper
Reinier Hasper

Reputation: 21

use virtual method of base class C++ in child of child class

I've created a class named 'Device' which get inherited by multiple devices (for example, RFDevice, AccelleroDevice)

The Device class inherited a Thread class. This Threadclass includes a Pure virtual function named run. Is it possible to accesss this pure virtual function in RFDevice or AcelleroDevice.

So,

ThreadClass->DeviceClass->RFDeviceClass.

I've tried to add

' virtual void run(void) = 0' also in the device class but this wont work.

Greets,

Upvotes: 2

Views: 1936

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27538

Only if the virtual function is not private. If it is, then you cannot call it and are not supposed to, either:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
private:
    virtual void run() = 0;
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
public:
    void f()
    {
        run(); // compiler error
    }
};

If it is protected or public, then it will work, provided there is an implementation of the function somewhere down the class hierarchy. But with the exception of the destructor, virtual functions should rarely be public or protected in C++:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
protected:
    virtual void run() = 0; // non-private virtual, strange
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
protected:
    virtual void run()
    {
    }

public:

    void f()
    {
        run(); // works
    }
};

Of course, this does not technically call the base function. And that's a good thing; you'd end up with a pure virtual function call otherwise, and your program would crash.

Perhaps what you need to do is to just implement the private virtual function. That would be the preferred class design:

class ThreadClass
{
public:
    virtual ~ThreadClass() {}
    void execute()
    {
        run();
    }
private:
    virtual void run() = 0;
};

class Device : public ThreadClass
{
};

class RFDevice : public Device
{
private:
    virtual void run()
    {
    }
};

int main()
{
    RFDevice d;
    d.execute();
}

If you are not just maintaining a legacy code base, you should probably get rid of your thread class and use C++11 multi-threading.

Upvotes: 4

Related Questions