Virtual functions clarifications

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vermarajeev
    New Member
    • Aug 2006
    • 180

    Virtual functions clarifications

    Hi guys,
    I have problem understanding virtual functions??? Like how it works.

    My friend asked me some questions

    1) What is a static function???
    I replied functions to be used without intantiating an object of that class.

    2) Can static function be called using this pointer???
    I told no!!! but I dont know why??? This is because my funda is not clear.
    Need some exaplantion about why???. If possible using day to day life example as like Ganon11 (where I say his explanation for pure virtual functions). It was really good one.

    3) What is virtual function???
    I know the defination (from book) but the funda is not clear. Please explain with day to day life example .

    4) Can virtual functions be made static????

    5) Can i call a virtual function from within a constructor????

    These are some of the questions I have and I need to make them clear. Please help

    Thanks in advance
  • Sandro Bosio
    New Member
    • Mar 2007
    • 4

    #2
    A short reply to some questions (question 3 is quite long to be properly answered, and you can find good explanations both on the web and on books).

    1) Your answer is right. And you can use only static and local variables within a static function.

    2) Yes, they are class members. But you just have to try to find out.

    3) Short answer: they are functions which a derived class can redefine. Then at runtime the "most new" version (i.e., those of the derived class) of the function will be called (unless you explicitly specify which one you are going to call), no matter from where the function is called.
    Pure virtual functions (with =0 at the end of the function declaration) are the same as virtual functions, but you don't define them in the base class. You just declare them. Therefore you cannot instantiate objects of the base class, since there are undefined functions.

    But there are more details to find out, just google for virtual functions and pure virtual functions.

    4) No, I don't know exactly why. But again, just try and find out.

    5) Obviously yes, it is a function like all the others.

    Sandro

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      Originally posted by Sandro Bosio
      3) Short answer: they are functions which a derived class can redefine. Then at runtime the "most new" version (i.e., those of the derived class) of the function will be called (unless you explicitly specify which one you are going to call), no matter from where the function is called.
      Actually, they are functions which a derived class must define. Any derived class can override any base class's function, but it has the option of doing so. Declaring a function as virtual requires subclasses to redefine the function.

      At runtime, the 'most new' version is not necessarily the one that is called. For instance, suppose you have two classes, Base and Derived. In Base, you declare a virtual function called function(). Thus, Derived must have function() also. The way you answered, the Derived::functi on() would always be called, since it is the "most new". But if you have an object of type Base and you call function(), the Base::function( ) is used. When you call function() on any Base or Derived object, the computer determines which class the object is and uses the appropriate function.

      Comment

      • vermarajeev
        New Member
        • Aug 2006
        • 180

        #4
        For instance, suppose you have two classes, Base and Derived. In Base, you declare a virtual function called function(). Thus, Derived must have function() also
        Are you sure this statement is correct. If yes

        Code:
        class A
        {
          public:
                  A(){}
                  virtual void func()
                  {
                     cout<<"A's func()"<<endl;
                  }
        };
        
        class B : public A
        {
        public:
                  B(){}
        }; 
        
        void userFunc( A* obj )
        {
           obj->func();
        }
        
        int main()
        {
           A a;
           B b;
           userFunc( &a );
           return 0;
        }
        Here class B derived from A doesnt have a function func();

        I'm totally confused now....Please guys....

        Comment

        • dmjpro
          Top Contributor
          • Jan 2007
          • 2476

          #5
          hello if the derived class don't override the base class function then the derived class uses the base class version........ .

          Comment

          • vermarajeev
            New Member
            • Aug 2006
            • 180

            #6
            Originally posted by dmjpro
            hello if the derived class don't override the base class function then the derived class uses the base class version........ .
            Hi dmjpro,
            Can you please be more specific??? If possible with example given in above post.

            Thanks in advance

            Comment

            • dmjpro
              Top Contributor
              • Jan 2007
              • 2476

              #7
              Originally posted by vermarajeev
              Hi guys,
              I have problem understanding virtual functions??? Like how it works.

              My friend asked me some questions

              1) What is a static function???
              I replied functions to be used without intantiating an object of that class.

              2) Can static function be called using this pointer???
              I told no!!! but I dont know why??? This is because my funda is not clear.
              Need some exaplantion about why???. If possible using day to day life example as like Ganon11 (where I say his explanation for pure virtual functions). It was really good one.

              3) What is virtual function???
              I know the defination (from book) but the funda is not clear. Please explain with day to day life example .

              4) Can virtual functions be made static????

              5) Can i call a virtual function from within a constructor????

              These are some of the questions I have and I need to make them clear. Please help

              Thanks in advance

              2.because this is silently generated when the object is created .... but in the static function there is no surity of object creation..... so u can't access this from static function.

              3.virtual functions are those function which are bound by the run time system at run time.....
              if u don't specify a method as virtual then compiler decides to run at compilation time.....

              the virual function is manatained by VPTR which silently inserted by Compiler and resolved by run time system

              know one thing the static funciton never be inherited so it is virtual does not make any sense.....

              u can't call virtual function inside constructor .. because inside the constructor the VPTR mechanism inserted.... i think it may work ... but it is not safe

              welcome .....

              Comment

              • vermarajeev
                New Member
                • Aug 2006
                • 180

                #8
                Wow!!! This is what I wanted... Thanks a lot

                I have some more doubts from above.

                virtual functions are those function which are bound by the run time system at run time.....
                if u don't specify a method as virtual then compiler decides to run at compilation time
                So you mean to say, member functions are selected based on type of object rather than pointer/reference to that object.

                I would be happy if you could explain me how this VPTR works. Suppose I have a class Base and a class Derived. There are two virtual functions defined in class Base, these two methods are overridden in Derived class. How is that the VPTR comes into picture????

                know one thing the static funciton never be inherited so it is virtual does not make any sense.....
                This is really useful NOTE for me...

                1) Another question!! I know what a virtual destructor is.. I would like to know what is the use of pure virtual destructor??? Is it necessary that for virtual destructor there has to be a virtual constructor????

                Thanks in advance

                Comment

                • dmjpro
                  Top Contributor
                  • Jan 2007
                  • 2476

                  #9
                  the VPTR is a pointer to the all virtual functions of that class....

                  the run time system will get the run time actual object type.....

                  then from that address the VPTR is retrieved and take the decision which function version will get called ....

                  m i clear .......

                  Comment

                  • dmjpro
                    Top Contributor
                    • Jan 2007
                    • 2476

                    #10
                    know one thing ... i started after totally detached from C++ for one year...

                    so right now i can't clearify the destructor .. actually i am working on J2EE

                    but after 10-15 days i wil be as i was before one year ......

                    okkkkkk... so look for another expert and have a good day......

                    Comment

                    • Banfa
                      Recognized Expert Expert
                      • Feb 2006
                      • 9067

                      #11
                      Originally posted by Ganon11
                      Actually, they are functions which a derived class must define. Any derived class can override any base class's function, but it has the option of doing so. Declaring a function as virtual requires subclasses to redefine the function.
                      Err actually Ganon this just isn't true. I did have to look this up to be sure about it but from section 12.2.6 of "The C++ Programming Language" by B. Stroustrup
                      Originally posted by The C++ Programming Language
                      A virtual function can beused even if no class is derived from its class, and a derived class that does not need its own version of a virtual function need not provide one. When deriving a class, simply provide an appropriate function, if it is needed.
                      So a class is not required to redefine a function that is declared virtual in one of its parent classes, but it may if it needs to.

                      The big difference is that when a function is declared virtual you are guaranteed that the correct function for the object will be called regardless of the type of the reference it is called through.

                      As illustrated in the difference between PrintMe and PrintMsg in the program below. PrintHelloWorld is an example of a non over ridden virtual function.

                      Note:

                      If you fail to override a pure virtual function inherited from an abstract parent class then the derived class will also be abstract since it will contain a pure virtual function.

                      If you declare any functions virtual it is good practice to declare the destructor virtual too.

                      Code:
                      #include "iostream"
                      using namespace std;
                      
                      class Base
                      {
                      public:
                          virtual void PrintMe(){ cout << "Base" << endl; }
                          virtual void PrintHelloWorld(){ cout << "Hello World" << endl; }
                          void PrintMsg(){ cout << "I'm in Base" << endl; }
                      
                          Base(){};
                          virtual ~Base(){};
                      };
                      
                      class Derived : public Base
                      {
                      public:
                          virtual void PrintMe(){ cout << "Derived" << endl; }
                          void PrintMsg(){ cout << "I'm in Derived" << endl; }
                      
                          Derived(){};
                          virtual ~Derived(){};
                      };
                      
                      int main()
                      {
                          Derived d;
                          Base &rb = d;
                      
                          rb.PrintMe();
                          rb.PrintHelloWorld();
                          rb.PrintMsg();
                      
                          return 0;
                      }

                      Comment

                      • Ganon11
                        Recognized Expert Specialist
                        • Oct 2006
                        • 3651

                        #12
                        Originally posted by Banfa
                        Err actually Ganon this just isn't true.7
                        Hrm. I, also, had to look this up to make sure, but you're right. I guess that was a leftover confusion from working with abstract in Java, where there was no 'virtual' option, only the equivalent of pure virtual. Sorry for any confusion caused.

                        Comment

                        • vermarajeev
                          New Member
                          • Aug 2006
                          • 180

                          #13
                          Firstly thanks to dmjpro for a quick and comforting reply.

                          Hi Banfa,
                          Thanks for your satisfying reply. Now my concept is becoming more clearer.

                          But still this questions are to be answered..

                          1)I would like to know what is the use of pure virtual destructor???

                          2)About VPTR. dmjpro has already explained about it in the previous post but still I'm unclear and has not got a clear picture.

                          Could you please help me to understand above two questions.

                          Thanks

                          Comment

                          • dmjpro
                            Top Contributor
                            • Jan 2007
                            • 2476

                            #14
                            look at this code what compiler inserts silently......

                            Code:
                            class A
                            {
                               void * VPTR = holds the address of the off all virual funations of class A
                               //some code
                               virtual void fun()
                               {
                                  //Class A function fun
                               }
                               //some code
                            };
                            
                            class B : public A
                            {
                               void * VPTR = holds the address of the off all virual funations of class B
                               //some code
                               virtual void fun()
                               {
                                  //Class B function fun
                               }
                               //some code
                            };
                            
                            //some code .....
                            B b;
                            A a;
                            A *ap = &b;
                            ap->fun();//here now ap holds the address of class B object and the corresponding VPTR retrieved and actual adress of [B]fun[/B] function retrieved and gets called
                            
                            //similarly solved if ...... ap = &a and ap->fun();
                            okk .... i think now u got my point .....

                            welcome again...... have a good day...
                            Last edited by Ganon11; Mar 16 '07, 11:49 AM. Reason: code tags added, indented

                            Comment

                            • vermarajeev
                              New Member
                              • Aug 2006
                              • 180

                              #15
                              Thanks.... Now it gives a clear picture.

                              Thanks again

                              Comment

                              Working...