Go Back   CodeCall Programming Forum > Software Development > Tutorials > C Tutorials
Register Blogs Search Today's Posts Mark Forums Read

C Tutorials All C Tutorials and Code

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-12-2009, 06:10 PM
ZekeDragon's Avatar
Code Warrior
 
Join Date: Jul 2009
Location: Nowhere, Washington
Posts: 1,721
ZekeDragon is a name known to allZekeDragon is a name known to allZekeDragon is a name known to allZekeDragon is a name known to allZekeDragon is a name known to allZekeDragon is a name known to all
Send a message via AIM to ZekeDragon Send a message via MSN to ZekeDragon Send a message via Skype™ to ZekeDragon
Virtual Functions and Polymorphism

It occured to me that with the STL series I'm working on, it might be important to talk a little bit about Virtual functions. Declaring functions as virtual makes the use of classes easier to manage, and allows for polymorphism, a central tenet of Object-Oriented programming. I know that these kinds of topics are difficult for newer programmers to pick up, and as such, I'll attempt to explain it as simply and with as much detail as possible to help people understand. Polymorphism, to put it rather simply, means that a derived class (a class that inherits properties from a base class) is able to change what a function declared as virtual in the base class actually does. We'll take the code example below as a set of classes that do NOT exhibit polymorphism.
C++ Code:
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class simpleClass
  5. {
  6. protected:
  7.     int numby;
  8. public:
  9.     simpleClass(int x) : numby(x)
  10.     {}
  11.     // NO virtual function declared here.
  12.     void show() { cout << "Class Num: " << numby << endl; }
  13. };
  14.  
  15. class derivedClass : public simpleClass
  16. {
  17. public:
  18.     derivedClass(int x) : simpleClass(x)
  19.     {}
  20.  
  21.     void show() { cout << "Class Num Doubled: " << numby * 2 << endl; }
  22. };
  23.  
  24. class anotherDerivedClass : public derivedClass
  25. {
  26. public:
  27.     anotherDerivedClass(int x) : derivedClass(x)
  28.     {}
  29.  
  30.     void show() { cout << "Class Num Tripled: " << numby * 3 << endl; }
  31. };
  32.  
  33. void func(simpleClass& obj)
  34. {
  35.     cout << "'Func' Shows:      ";
  36.     obj.show();
  37. }
  38.  
  39. int main() {
  40.     simpleClass cls(100);
  41.     derivedClass cls2(100);
  42.     anotherDerivedClass cls3(100);
  43.     cout << "Class cls Shows:   ";
  44.     cls.show();
  45.     func(cls);
  46.     cout << endl << "Class cls2 Shows:  ";
  47.     cls2.show();
  48.     func(cls2);
  49.     cout << endl << "Class cls3 Shows:  ";
  50.     cls3.show();
  51.     func(cls3);
  52. }
If you run this code, you'll end up with this.
Code:
Class cls Shows:   Class Num: 100
'Func' Shows:      Class Num: 100

Class cls2 Shows:  Class Num Doubled: 200
'Func' Shows:      Class Num: 100

Class cls3 Shows:  Class Num Tripled: 300
'Func' Shows:      Class Num: 100
The function func requests a simpleClass reference, which as you can see when virtual is not used, the function simply calls the simpleClass version of the show function each time it is called, regardless of whether or not the base class OR one of the derived classes is used in the call. Sometimes this is what you want, but usually, it's not. So how can we get func to call our derived classes versions of show? Easy, we declare in the base class that show is a virtual function! Just add this small amount to the code in the following code snippet, in context:
C++ Code:
  1. class simpleClass
  2. {
  3. protected:
  4.     int numby;
  5. public:
  6.     simpleClass(int x) : numby(x)
  7.     {}
  8.     // Now this class method is virtual!
  9.     virtual void show() { cout << "Class Num: " << numby << endl; }
  10. };
NOW when you run the same program, not changing any other code, you'll end up with this...
Code:
Class cls Shows:   Class Num: 100
'Func' Shows:      Class Num: 100

Class cls2 Shows:  Class Num Doubled: 200
'Func' Shows:      Class Num Doubled: 200

Class cls3 Shows:  Class Num Tripled: 300
'Func' Shows:      Class Num Tripled: 300
When func is called, it figures out based on which class was passed as a parameter to func which version of show to use! You'll also notice that you don't need to give it's derived class methods a virtual keyword either, since it always acts as virtual from there on.

So, what if you want to use the base classes version of show in the func function? Is that impossible? Not at all! Let's add another line of code to exemplify this, changing the func function now:
C++ Code:
  1. void func(simpleClass& obj)
  2. {
  3.     cout << "'Func' Shows:      ";
  4.     obj.show();
  5.     cout << "                   ";
  6.     obj.simpleClass::show();
  7. }
When you run the program now, your output will look like this:
Code:
Class cls Shows:   Class Num: 100
'Func' Shows:      Class Num: 100
                   Class Num: 100

Class cls2 Shows:  Class Num Doubled: 200
'Func' Shows:      Class Num Doubled: 200
                   Class Num: 100

Class cls3 Shows:  Class Num Tripled: 300
'Func' Shows:      Class Num Tripled: 300
                   Class Num: 100
When you add the "obj.simpleClass::show();" line, the compiler realizes you're using specifically the simpleClass namespace for the show function, and so despite show being declared as virtual, it still uses the base class version instead of the derived classes versions.

Finally, in the case of abstract classes (IE classes that aren't supposed to be declared and implemented in themselves, and are only supposed to be inherited by other derived classes), you can define virtual functions as such, and allow each derived class to implement their own version of that function:
C++ Code:
  1. class simpleClass
  2. {
  3. protected:
  4.     int numby;
  5. public:
  6.     simpleClass(int x) : numby(x)
  7.     {}
  8.     // Now this class method is abstract!
  9.     virtual void show() = 0;
  10. };
This changes the function into an abstract method and in turn, the class an abstract class. If you try to declare an object as simpleClass now, the compiler will complain that you cannot declare an abstract class, so DO NOT USE THIS CODE IN THE ABOVE EXAMPLE, IT WILL NOT WORK! (unless you change it around so that there are no references to the simpleClass version of show and no direct declarations of simpleClass.)

Hope you learned something about the virtual function, and maybe a little more about how polymorphism works!
__________________
On Hiatus...
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 08-12-2009, 06:47 PM
Jordan's Avatar
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 24,556
Jordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to all
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan Send a message via Yahoo to Jordan
Re: Virtual Functions and Polymorphism

Very nice! +rep
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-12-2009, 09:24 PM
marwex89's Avatar
Code Warrior
 
Join Date: Jul 2008
Location: Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
Posts: 9,849
marwex89 is a glorious beacon of lightmarwex89 is a glorious beacon of lightmarwex89 is a glorious beacon of lightmarwex89 is a glorious beacon of lightmarwex89 is a glorious beacon of lightmarwex89 is a glorious beacon of light
Send a message via AIM to marwex89 Send a message via MSN to marwex89
Re: Virtual Functions and Polymorphism

Nice +rep
__________________

Computers make very fast, very accurate mistakes.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 08-12-2009, 09:54 PM
WingedPanther's Avatar
Super Moderator
 
Join Date: Jul 2006
Age: 36
Posts: 11,435
WingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud of
Re: Virtual Functions and Polymorphism

Nice little demo +rep
__________________
CodeCall Blog | CodeCall Wiki | Shareware
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 08-24-2009, 12:50 AM
Turk4n's Avatar
Code Warrior
 
Join Date: May 2008
Location: 4chan.org/g/
Age: 20
Posts: 3,822
Turk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud of
Send a message via MSN to Turk4n Send a message via Skype™ to Turk4n
Re: Virtual Functions and Polymorphism

Simple and neat !
rep+
__________________

Hatsune Miku ~❤❤❤
初音ミク。~❤❤❤
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 08-24-2009, 02:51 AM
MathX's Avatar
Guru
 
Join Date: Oct 2008
Location: Kosovo
Age: 19
Posts: 3,994
MathX has a spectacular aura aboutMathX has a spectacular aura about
Send a message via MSN to MathX
Re: Virtual Functions and Polymorphism

I cannot +rep you right now, nicely done though!
__________________
My Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Tags
c++, polymorphism, virtual keyword



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Subclasses & virtual functions RobotGymnast C and C++ 7 12-13-2008 09:54 PM


All times are GMT -5. The time now is 08:22 AM.


vBulletin v3.8.0 ©2010, Jelsoft Enterprises Ltd.


no new posts

LinkBacks Enabled by vBSEO 3.1.0