Monday, December 01, 2003

Polymorphism: C++ vs Java vs C#

As mentioned earlier, all three languages provide support for polymorphism. But to enable it, each language requires different syntax.

C++ as we've seen requires a "virtual" keyword in the base class. To override this virtual method you only require to declare a method with the same signature in a derived class. The "virtual" keyword is optional.

class Base
virtual void fun() { std::cout << "Base::fun"; }

class Derived : public Base
/* virtual */ void fun() { std::cout << "Derived::fun"; }

void fun2() { std::cout << "Derived::fun2"; }

Base* p;

p = new Base;
p->fun(); // Base's fun()

p = new Derived;
p->fun(); // Derived's fun()

In Java, ALL methods are virtual by default. NO extra keywords are required to enable polymorphism.

public class Base
public void fun() { System.out.print( "" ); }

public class Derived extends Base
public void fun() { System.out.print( "" ); }

public void fun2() { System.out.print( "Derived.fun2" ); }

Base p;

p = new Base();; // Base's fun()

p = new Derived();; // Derived's fun()

In C# you need TWO keywords to enable polymorphism. In the base class you have to declare a function to be virtual using "virtual". In a derived class you have to explicitly specify that you intend to override a method using "override".

public class Base
public virtual void fun() { System.Console.Write( "" ); }

public class Derived : Base
public override void fun() { System.Console.Write( "" ); }

public void fun2() { System.Console.Write( "Derived.fun2" ); }

Base p;

p = new Base();; // Base's fun()

p = new Derived();; // Derived's fun()

It's interesting to compare and constract between the different languages and to understand why they chose to do what they did.

C++, as always, is most concerned about space and efficiency. It will ONLY have the overhead of the vtable pointer IF you have any virtuals in there. All methods will be resolved at compile time, statically, by default, unless they are virtual.

Java, on the other hand, concerned most with simplicity, defines all methods virtual. This means that ALL classes regardless of whether they need it or not will have v-tables. Efficiency suffers since ALL method calls will have an indirection. You could explicitly include the keyword "final" which is really the opposite of virtual. This will make the call static and will allow the compiler to resolve it at compile time. So, in Java, all methods will be resolved at run time, dynamically, by default, unless they are final.

Finally we have C#, which goes back to C++ roots. It too will have v-tables ONLY if there are virtual functions in the class. But why introduce the "override" keyword? This is to help with versioning of components. Consider this...

You develop a class which has a bunch of virtual methods. You derive from that class and override whatever you need. All is good... the derived class behaves well. Now, you also define a completely independant new method in the derived class. Sometime later, the Base class designer decides to add a new virtual method with that same name to the Base class. Now, that completely independant method in the Derived class is "unintentially" overriding the new Base class virtual method. More likely than not, it is NOT the correct behavior since it had no idea it was overriding anything. This will happen in both C++ as well as in Java. More easily in Java, since ALL methods are virtual by default. In C++, you have to explicitly say that it's virtual. C# won't have this problem since, you need the "override" keyword in the derived classes.

Extending the above examples...

In C++, if you add a new virtual method to the Base class...

virtual void fun2() { std::cout << "Base::fun2;" }

and in Java if you add a new method to the Base class...

public void fun2() { System.out.print( "Base.fun2" ); }

then the corresponding fun2()'s in Derived will automatically override these.

If you add a new virtual method to the Base class in C#

public virtual void fun2() { System.Console.Write( "Base.fun2" ); }

the compiler will generate a warning (NOT error) telling you that you need to be more explicit about what you are intending to do. Either add the "override" keyword to the derived class method fun2() saying that you DO want polymorphic behavior OR add the "new" keyword saying that you DON'T want polymorphic behavior and that you just want to shadow Base's fun2().


wow power leveling said...

welcome to the wow power leveling, cheap service site, buy cheap wow gold,wow gold,world of warcraft power leveling buy wow power leveling

Anonymous said...

Excellent article.

hitesh kumar said...

Polymorphism in java
this blog is simple and helpful

Anonymous said...

polymorphism in c++
Thanks for sharing this post

hitesh kumar said...

Polymorphism in C++

Great post

Unknown said...

This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

Love from

Unknown said...

This cleared things up for me, thanks :)

Rachel Lancaster said...

Nice Article!_

katetech said...

Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
application developers in hyderabad
ios app development company in hyderabad
mobile app development in gachibowli
bmobile app development in kukatpally
mobile app development in ameerpet

sandeep saxena said...

Thanks for sharing this article with us. Keep sharing your ideas with us.
core java training in chennai
Best core java Training in Chennai
core java Training in OMR
C Training in Chennai
javascript training in chennai
Appium Training in Chennai
JMeter Training in Chennai

anushya said...

Superb ! Your blog is incredible. I am impressed with it. Thanks for sharing this content under this topic.
Seo Training in Bangalore
Best Seo Training in Bangalore
Data Analytics Courses in Bangalore
Data Science Courses in Bangalore
Digital Marketing Courses in Bangalore
German Classes in Bangalore
Python Training in Bangalore
Selenium Training in Bangalore

Unknown said...

Awesome blog thanks for sharing While choosing your perfect ride for driving, Accord Cars comes with and the best packages for you to pick from. Car rentals for self drive in Chennai are done the easier. Just pick out your plan from hourly, daily, weekly and even monthly plans available.

Unknown said...

Very useful blog thanks for sharing With over a three decade of beauty expertise at our fingertips, we believed that everyone has the right to be beautiful. And so began the journey of our very own Pearl’s Beautician course in Chennai.

Adhuntt said...

Great blog thanks for sharing Looking for the best creative agency to fuel new brand ideas? Adhuntt Media is not just a digital marketing company in chennai. We specialize in revamping your brand identity to drive in best traffic that converts.

Karuna said...

Nice blog thanks for sharing Set up a aesthetic work environment that employees love to spend time in and relieve their stress. Your company needs the best corporate gardening service in Chennai and Karuna Nursery Gardens in happy to oblige you in the endeavour to make your infrastructure something worth flaunting about.

Pixies said...

Excellent blog thanks for sharing Run your salon business successfully by tying up with the best beauty shop in Chennai - The Pixies Beauty Shop. With tons of prestigious brands to choose from, and amazing offers we’ll have you amazed.

Extensiya said...

Awesome blog thankks for sharing 100% virgin Remy Hair Extension in USA, importing from India. Premium and original human hair without joints and bondings. Available in Wigs, Frontal, Wavy, Closure, Bundle, Curly, straight and customized color hairstyles Extensions.

Indpac said...

Very useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.

merlin said...

such a great blog thank you for share this great information.
Selenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery

latchu kannan said...

This is the best article that I had seen ever. I lot of gained a lot of knowledge by reading your article.
AngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery

Rashika said...

The given information was excellent and useful.
This is one of the excellent blog, I have come across.

Digital Marketing Training in Chennai | Certification | SEO Training Course | Digital Marketing Training in Bangalore | Certification | SEO Training Course | Digital Marketing Training in Hyderabad | Certification | SEO Training Course | Digital Marketing Training in Coimbatore | Certification | SEO Training Course | Digital Marketing Online Training | Certification | SEO Online Training Course

jegan said...

wonderful article contains lot of valuable information. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
This article resolved my all queries.good luck an best wishes to the team members.continue posting.learn digital marketing use these following link
Digital Marketing Course in Chennai