Reputation: 211
I am implementing a pure virtual function from a parent class in a subclass.
When I try to instantiate the subclass in eclipse it says
The type 'derived' must implement the inherited pure virtual method 'Base::compareTo'
I am pretty sure I did so. My base class is..
base.h
#ifndef BASE_H_
#define BASE
class Base{
public:
Base();
virtual ~Base();
virtual int compareTo(void* compare)=0;
};
#endif /* BASE*/
Then my derived.h
#ifndef DERIVED_H_
#define DERIVED_H_
#include "Base.h"
class Derived : public Base {
public:
int x;
Derived(int y);
virtual ~Derived();
int compareTo(void* compare);
};
#endif /* DERIVED_H_ */
Derived.cpp
#include "Derived.h"
#include "Base.h"
Derived::Derived(int y) {
// TODO Auto-generated constructor stub
x=y;
}
Derived::~Derived() {
// TODO Auto-generated destructor stub
}
int Derived::compareTo(void* compare) {
Derived* compared;
int result=0;
if(compared=dynamic_cast<Derived*>(compare))
{
if(x<compared->x)
{
result=-1;
}
else
{
result=1;
}
}
return result;
}
Upvotes: 1
Views: 1601
Reputation: 9
try this code of Base class:
#ifndef BASE_H_
#define BASE_H_
class Base{
public:
//Base (); not needed in the virtual class
virtual ~Base() {};
virtual int compareTo(void* compare)=0;
};
#endif /* BASE*/
#ifndef DERIVED_H_
#define DERIVED_H_
#include "Base.h"
class Derived : public Base {
public:
int x;
Derived(int y);
virtual ~Derived();
int compareTo(void* compare) override/*C++11*/;
};
#endif /* DERIVED_H_ */
#include "Derived.h"
//#include "Base.h" Not needed
Derived::Derived(int y) {
// TODO Auto-generated constructor stub
x=y;
}
Derived::~Derived() {
// TODO Auto-generated destructor stub
}
int Derived::compareTo(void* compare) {
Derived* compared;
int result=0;
if(compared=dynamic_cast<Derived*>(compare))
{
if(x<compared->x)
{
result=-1;
}
else
{
result=1;
}
}
return result;
}
Upvotes: 0
Reputation: 238311
I'm assuming this message is from eclipses code analyzer and not from your compiler. The code analyzer is wrong and you are correct. You have correctly implemented the pure virtual method from the base class in Derived
. If you try to instantiate Derived, the code should compile.
Might your CDT version be less than 8.2.1? If so, you may be encountering this bug which should be fixed in 8.2.1.
There is another bug in your code though. You can't dynamic_cast a void pointer.
Upvotes: 1