Search code examples
c++inheritancevirtualpure-virtual

override pure virtual function not possible with const struct timepec*


Below is my Pure virtual Interface class that I want to Implement:

#include <time.h>
class SharedMemoryInterface
{
public:
    virtual ~SharedMemoryInterface() {}
    virtual int sem_timedwait(sem_t* sem, const struct timepsec* abs_timeout) = 0; 
};

Below is the implementation:

class SharedMemoryImpl : public SharedMemoryInterface
{
public:
    virtual int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout) { return ::sem_timedwait(sem, abs_timeout); }
};

I get the compiler error:

SharedMemoryImpl.h:25:7: note:   because the following virtual functions are pure within "SharedMemoryImpl":
 class SharedMemoryImpl : public SharedMemoryInterface
SharedMemoryInterface.h:27:17: note:    virtual int SharedMemoryInterface::sem_timedwait(sem_t*, const timepsec*)
     virtual int sem_timedwait(sem_t* sem, const struct timepsec* abs_timeout) = 0;

The only difference seems to be in the timespec parameter, it removes the struct and the prototypes do not match anymore, why is it doing this?


Solution

  • You have a typo in SharedMemoryInterface::sem_timedwait: you wrote timepsec instead of timespec.

    Normally this would cause an error, but you used the struct keyword. When the compiler sees struct timepsec, it either finds a struct named timepsec (ignoring any functions with the same name) or forward-declares a new one if it doesn't find it. So, the use of struct masks the typo. When you spell timespec correctly in SharedMemoryImpl, of course it refers to a different type. So the pure virtual function in SharedMemoryInterface isn't overridden.

    AFAIK, there isn't a compiler warning that catches these misspelled forward declarations. In C++, I would suggest that it's a good practice to simply avoid elaborated type specifiers, unless you really need your code to compile in both C and C++ (obviously, that's not the case here) or you need to refer to a struct/class with the same name as a function (obviously, it's bad to name things this way, but C libraries do it sometimes).