Reputation: 29178
I am new to C++. Could you pls help me get rid of the errors:
error C2259: 'MinHeap' : cannot instantiate abstract class
IntelliSense: return type is not identical to nor covariant with return type "const int &" of overridden virtual function function
template <class T> class DataStructure {
public:
virtual ~DataStructure () {}
virtual bool IsEmpty () const = 0;
virtual void Push(const T&) = 0;
virtual const T& Top() const = 0;
virtual void Pop () = 0;
};
class MinHeap : public DataStructure<int>
{
private:
std::vector<int> A;
public:
bool IsEmpty() const
{
..
}
int Top() const
{
..
}
void Push(int item)
{
...
}
void Pop()
{
..
}
};
Upvotes: 4
Views: 8713
Reputation: 1130
(The errors are due to a signature mismatch in function Push
and in function Top
)
--
Modern C++
C++11 adds two inheritance control keywords: override
and final
. It is advisable to use either the override or final specifier when declaring an overridden function. Two common issues associated with overriding virtual functions are: Inadvertent overriding and Signature mismatch (Your case).
override
ensures that an overriding virtual function declared in a derived class has the same signature as that of the base class. final
blocks further overriding of a virtual function and further derivation of a class.
Example:
#include <vector>
template <class T>
class DataStructure
{
public:
virtual ~DataStructure() = default;
virtual bool IsEmpty() const = 0;
virtual void Push(const T&) = 0;
virtual const T& Top() const = 0;
virtual void Pop() = 0;
};
class MinHeap final : public DataStructure<int> // <--
{
private:
std::vector<int> a_;
public:
bool IsEmpty() const override // <--
{
// Do something
return true;
}
void Push(const int& item) override // <-- (Signature mismatch fixed)
{
// Do something
}
const int& Top() const override // <-- (Signature mismatch fixed)
{
// Do something
return 0;
}
void Pop() override // <--
{
// Do something
}
};
Upvotes: 0
Reputation: 25381
try
class MinHeap : public DataStructure<int>
{
private:
std::vector<int> A;
public:
bool IsEmpty() const
{
..
}
const int& Top() const
{
..
}
void Push(const int& item)
{
...
}
void Pop()
{
..
}
};
Note that it is using const int&
instead of int
for Top and Push
Upvotes: 2
Reputation: 224049
The problem is with const T& Top()
vs. int Top()
. The latter is different from the former, and thus not an override. Instead it hides the base class function. You need to return exactly the same as in the base class version: const int& Top() const
.
The same problem exists for Push()
, BTW.
Upvotes: 9