Object::ToString was not virtual in VS 2012 and thus could not be overridden, and this was a bit of an inconvenience when databinding with XAML. Tarek Madkour’s Build 2013 talk on what’s new in VS 2013 for C++ Developers had a slide about overriding ToString. While that was exciting to see, I was a tad disappointed when I could not get it to compile under the VS 2013 preview build. The following code fails to compile.
ref class Person sealed
{
public:
virtual String^ ToString() override
{
return "Test override";
}
};
The error thrown is : Error 1 error C3668: ‘Person::ToString’ : method with override specifier ‘override’ did not override any base class methods
I am hoping that it just never made it to the preview release and that the RTM version will have it, as it can be quite handy to be able to override ToString, and not just in XAML scenarios.
Nice tip! :]
handsome Our Site
Try removing sealed from the class declaration because I am able to compile and run code fine with overriden ToString() method even in VS 2012 Ultimate. This is class declaration:
ref class Test {
public:
virtual String^ ToString() override {
return “test override”;
}
};
I then call is like this:
Test t;
Console::WriteLine(“Test: ” + t.ToString());
I receive output in the console with Test override and no compilation errors occur.
But when a make the class Test sealed, I get compiler error.
… or make your toString function sealed like this:
virtual String^ ToString() override sealed {
…
}
This removes compiler error because sealed classes cannot contain non-sealed virtual functions.