Question

I have a C++/CX Windows Store component class and I'd like to implement a custom public ToString method that I can invoke from C#. It compiles fine but I'm getting an odd warning from the compiler. Here is code that reproduces the warning:

public ref class Foo sealed
{
public:
    String^ ToString()
    {
        return ref new String(L"This is from class Foo");
    }
};

When I compile the above class Visual Studio 2013 shows this warning:

warning C4827: A public 'ToString' method with 0 parameters should be marked as virtual and override (Foo.cpp)

However when I add 'virtual override' on the method signature I get syntax errors in the compiler. How can I override Object.ToString() from a C++/CX class?

Was it helpful?

Solution

The virtual goes at the beginning, the override goes at the end. Also, you can get rid of the ref new String, the compiler can figure out that you want the string constant to be treated as a String^.

public ref class Foo sealed
{
public:
    virtual String^ ToString() override
    {
        return "This is from class Foo";
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top