Home » C# » C++ » Interview questions » Polymorphism » Polymorphism in C++ and C#

Polymorphism in C++ and C#

I went for an interview for a C++ job one time and they showed me the following code and asked me what the output would be:

Really this is a question about inheritance and polymorphism in C++. The class description is the base class and the classes sphere and cube inherit from it. Because the description has declared it’s method print() as virtual a vtable is created under the hood for that class and method. Any class that derives from description is allowed to override it’s definition of print() and use its own. The definition of the print() method must exactly match the base class’ print(). Whenever this happens the overriden method is put in the base class’ vtable. In this way it is always called instead of the base class print().

The output from the program is:

Now on to C#. Here’s the same question, but in the .NET world:

The output from this program is:

It’s different! What’s going on?!

When you compile the program you’ll notice 2 warning messages that come up:

Instead of overriding the base class’ print() method it has hidden it with it’s own. This means that when we recast the objects as description objects we get the base class version of print(). To get the same behaviour that we saw in C++ we have to use the override keyword when giving our method definitions. For both sphere and cube the print() method needs to be defined as:

With that change done you will get the same output as the C++ code.

Unfortunately in my interview I gave the C# answer for a C++ question! I was gutted when I realised what I’d done. I kept muttering in the interview “But there’s no override. There’s no override statement”. I thought it was a trick question, as most interview questions are. So I’ve put it here as a reminder for me – and maybe it will help someone else too.