+ Reply to Thread
Results 1 to 6 of 6

Thread: Virtual Functions and Polymorphism

  1. #1
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    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.
    Code:
    #include <iostream>
    using namespace std;
    
    class simpleClass
    {
    protected:
        int numby;
    public:
        simpleClass(int x) : numby(x)
        {}
        // NO virtual function declared here.
        void show() { cout << "Class Num: " << numby << endl; }
    };
    
    class derivedClass : public simpleClass
    {
    public:
        derivedClass(int x) : simpleClass(x)
        {}
    
        void show() { cout << "Class Num Doubled: " << numby * 2 << endl; }
    };
    
    class anotherDerivedClass : public derivedClass
    {
    public:
        anotherDerivedClass(int x) : derivedClass(x)
        {}
    
        void show() { cout << "Class Num Tripled: " << numby * 3 << endl; }
    };
    
    void func(simpleClass& obj)
    {
        cout << "'Func' Shows:      ";
        obj.show();
    }
    
    int main() {
        simpleClass cls(100);
        derivedClass cls2(100);
        anotherDerivedClass cls3(100);
        cout << "Class cls Shows:   ";
        cls.show();
        func(cls);
        cout << endl << "Class cls2 Shows:  ";
        cls2.show();
        func(cls2);
        cout << endl << "Class cls3 Shows:  ";
        cls3.show();
        func(cls3);
    }
    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:
    Code:
    class simpleClass
    {
    protected:
        int numby;
    public:
        simpleClass(int x) : numby(x)
        {}
        // Now this class method is virtual!
        virtual void show() { cout << "Class Num: " << numby << endl; }
    };
    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:
    Code:
    void func(simpleClass& obj)
    {
        cout << "'Func' Shows:      ";
        obj.show();
        cout << "                   ";
        obj.simpleClass::show();
    }
    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:
    Code:
    class simpleClass
    {
    protected:
        int numby;
    public:
        simpleClass(int x) : numby(x)
        {}
        // Now this class method is abstract!
        virtual void show() = 0;
    };
    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!
    Last edited by ZekeDragon; 06-29-2011 at 11:43 AM.
    Wow I changed my sig!

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: Virtual Functions and Polymorphism

    Very nice! +rep

  4. #3
    Join Date
    Jul 2008
    Location
    Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
    Posts
    10,725
    Blog Entries
    2
    Rep Power
    90

    Re: Virtual Functions and Polymorphism

    Nice +rep
    Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

  5. #4
    Join Date
    Jul 2006
    Posts
    16,486
    Blog Entries
    75
    Rep Power
    143

    Re: Virtual Functions and Polymorphism

    Nice little demo +rep
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  6. #5
    Join Date
    May 2008
    Location
    Hell
    Posts
    3,851
    Blog Entries
    4
    Rep Power
    49

    Re: Virtual Functions and Polymorphism

    Simple and neat !
    rep+

  7. #6
    Join Date
    Oct 2008
    Location
    Istog, Kosova
    Posts
    4,001
    Blog Entries
    1
    Rep Power
    40

    Re: Virtual Functions and Polymorphism

    I cannot +rep you right now, nicely done though!
    Interested in participating in community events?
    Want to harness your programming skill and turn it into absolute prowess?
    Come join our programming events!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Polymorphism
    By Turk4n in forum Java Tutorials
    Replies: 20
    Last Post: 08-01-2010, 07:38 PM
  2. Polymorphism
    By genux in forum PHP Tutorials
    Replies: 2
    Last Post: 02-05-2010, 11:24 AM
  3. Subclasses & virtual functions
    By RobotGymnast in forum C and C++
    Replies: 7
    Last Post: 12-13-2008, 06:54 PM
  4. virtual functions
    By Chinmoy in forum C Tutorials
    Replies: 0
    Last Post: 03-17-2008, 09:03 PM
  5. Virtual Functions ????
    By Patrick in forum C and C++
    Replies: 1
    Last Post: 10-07-2007, 07:54 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts