Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bother with virtual functions in c++?

This is not a question about how they work and declared, this I think is pretty much clear to me. The question is about why to implement this? I suppose the practical reason is to simplify bunch of other code to relate and declare their variables of base type, to handle objects and their specific methods from many other subclasses?

Could this be done by templating and typechecking, like I do it in Objective C? If so, what is more efficient? I find it confusing to declare object as one class and instantiate it as another, even if it is its child.

SOrry for stupid questions, but I havent done any real projects in C++ yet and since I am active Objective C developer (it is much smaller language thus relying heavily on SDK's functionalities, like OSX, iOS) I need to have clear view on any parallel ways of both cousins.

like image 336
poksi592 Avatar asked Mar 04 '11 10:03

poksi592


Video Answer


1 Answers

Yes, this can be done with templates, but then the caller must know what the actual type of the object is (the concrete class) and this increases coupling.

With virtual functions the caller doesn't need to know the actual class - it operates through a pointer to a base class, so you can compile the client once and the implementor can change the actual implementation as much as it wants and the client doesn't have to know about that as long as the interface is unchanged.

like image 123
sharptooth Avatar answered Oct 11 '22 20:10

sharptooth