+ Reply to Thread
Results 1 to 1 of 1

Thread: virtual functions

  1. #1
    Chinmoy's Avatar
    Chinmoy is offline Programming Expert
    Join Date
    Feb 2008
    Location
    where heaven meets earth
    Posts
    410
    Rep Power
    18

    virtual functions

    here i have discussed virtual functions using easy to understand examples.

    A virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. It is one that is declared as virtual in the base class using the virtual keyword. The virtual nature is inherited in the subsequent derived classes.

    The difference between a non-virtual member function and a virtual member function is, the non-virtual member functions are resolved at compile time whereas virtual members are resolved at runtime.

    in this code we have the implementation of virtual functions and their use in c++.

    Code:
    #include <iostream.h>
    class base
    {
    public:
    virtual void display()
    {
      cout<<”\nBase”;
    }
    };
    class derived : public base
    {
      public:
      void display()
      {
         cout<<”\nDerived”;
      }
    };
    
    void main()
    {
    
      base *ptr = new derived();
      ptr->display();
    }
    In the above example, the pointer is of type base but it points to the derived class object. The method display() is virtual in nature. Hence in order to resolve the virtual method call, the context of the pointer is considered, i.e., the display method of the derived class is called and not that of the base. If the method was non virtual in nature, the display() method of the base class would have been called.

    Virtual methods should be used judiciously as they are slow due to the overhead involved in searching the virtual table. They also increase the size of an object of a class by the size of a pointer.
    Last edited by Chinmoy; 03-18-2008 at 04:58 AM.

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

     
+ 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. Replies: 4
    Last Post: 02-06-2011, 01:37 PM
  2. SQL Functions - Math Functions
    By chili5 in forum Tutorials
    Replies: 6
    Last Post: 09-02-2009, 02:11 PM
  3. Virtual Functions and Polymorphism
    By ZekeDragon in forum C Tutorials
    Replies: 5
    Last Post: 08-23-2009, 11:51 PM
  4. Subclasses & virtual functions
    By RobotGymnast in forum C and C++
    Replies: 7
    Last Post: 12-13-2008, 06:54 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