NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Compiler Error C2555

'function1' of 'class1' : overriding virtual function differs from 'class2::function2' only by return type or calling convention

A virtual function and a derived overriding function have identical parameter lists but different return types. An overriding function in a derived class cannot differ from a virtual function in a base class only by its return type.

Possible solution

For more information on C2555, see Knowledge Base article Q240862.

Example

struct X
{
   virtual void func();
};
struct Y : X
{
   char func();  // error
};

Visual C++ does not support overriding a virtual function with a return type that differs in any way from the overridden function. The Visual C++ compiler does not support covariant return types. For example, the following two examples are not allowed in Visual C++,

// Example 1 
class A { 
public: 
   virtual A* func(); 
}; 

class B : public A { 
public: 
   virtual B* func(); 
}; 

//Example 2 
class C { 
public: 
   virtual A* func(); 
}; 
class D : public C { 
public: 
   virtual B* func(); 
};

You can mimic the behavior with a run-time performance loss by:

  1. Enable RTTI (/GR)
  2. Derive from a common base for the return type.
  3. Return the correct class type; do not use c-style cast or reinterpret_cast.
  4. Caller uses dynamic_cast to cast to the correct class
// Example 3 
class X {}; 
class A : public X { 
public: 
   virtual X* func() { return new A; } 
}; 
class B : public A { 
public: 
   virtual X* func() { return new B; } 
}; 
void test() { 
   X* p; 
   A a, *pa; 
   B b, *pb; 
   p = a.func(); 
   pa = dynamic_cast<A*>(p); 
   if (pa == 0) { /* error */ } 
   p = b.func(); 
   pb = dynamic_cast<B*>(p); 
   if (pb == 0) { /* error */ } 
}