Calling Virtual Function in a constructor

Jun 7, 2010 at 8:33pm
Consider the following code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  class base
        {
           base()
           {
                printfunction();
           }
           virtual void printfunction()
           {
                std::cout<< "I am base :)";
           }
        }

        class derived: public base
        {
            virtual void printfunction()
            {
               std::cout<<"derived here :( ";
            }
        }



Now when the object for a derived class is created, the output would be

I am a base



Is the output because the virtual pointer table is created after the constructor is called??
Jun 7, 2010 at 9:12pm
No. derived calls base's constructor, which, in turn, can only know about base's member functions, so it calls base's printfunction(). A base class knows nothing about its derived classes.

By the way, I suggest using the customary C++ convention of capitalizing user-defined type names. And you forgot the semicolons after your class declarations.
Jun 8, 2010 at 1:35am
@filipe: that's not correct. OP has it right. The virtual table of the derived is not filled out until
after the base is constructed, thus the call to the virtual printfunction() in the base class calls
the base class implementation. This is why you should never call virtual functions in a
constructor or a destructor.

Also, it is not necessarily "customary" to use capital letters for user-defined type names; that
is purely a coding style preference.

Jun 8, 2010 at 2:40pm
Oops. Sorry about that.

About the "customary", every book and most code I have read uses that convention. I understand it's just a preference, and that's precisely what a custom is.
Jun 8, 2010 at 3:02pm
I guess I objected to the phrase "C++ convention" and not "customary".

Whereas I agree with you that more programmers than not use capital letters in that way, you'll find there are
a lot that don't. I myself am a little schizophrenic when it comes to that. When I'm writing code professionally,
I usually use the capital letter, but not always. Around these forums, more and more I've been using lowercase.
Jun 9, 2010 at 3:18am
Thank You guys.... This forum is helping me a lot to get the basics rite..
Topic archived. No new replies allowed.