C++/CLI : How to override Equal method of Object class

KK. picture KK. · Dec 2, 2009 · Viewed 8.8k times · Source

I am a newbie to C++/CLI and is having some problems trying to override the Equal method of the base Object class. I get the following compilation warning error for the following code. How should this be corrected?

Warning 1   warning C4490: 'override' : incorrect use of override specifier; 'Test::Sample::Equal' does not match a base ref class method   c:\project\code\Sample.h    18  

Error   2   error LNK2022: metadata operation failed (80131187) : Inconsistent method declarations in duplicated types (types: Test.Sample; methods: Equal): (0x06000002).  Sample.obj

Edit 3: I changed "Equal" to "Equals", removed override keyword in source file but error 2 still stands.

// Header File

public ref class Sample : public Object
{
    public:
        int someVariable;

    virtual bool Equals(Object^ obj) override;
    virtual int GetHashCode() override;
}

// Source File

bool Sample::Equals(Object^ obj)
{ 
    if ( obj == nullptr || GetType() != obj->GetType() )
        return false;

    Sample^ p = dynamic_cast<Sample^>(obj);
    return (someVariable == p->someVariable);
}

int Sample::GetHashCode()
{
    return GetHashCode();
}

Answer

mmx picture mmx · Dec 2, 2009

The name of the method is not Equal, it's Equals. You shouldn't use virtual or override keywords in the implementation:

ref class Test {
public:
    virtual bool Equals(Object^ o) override; 
    virtual int GetHashCode() override;

};
bool Test::Equals(Object^ o) { // no "override" here 
    //...
}
int Test::GetHashCode() { // no "override" here
    //...
}