base class constructor are called before derived class construtors. Base* pBase = new Derived(); statement creates a derived class object hence calls derived class condstructor, which calls base call constructor. base class constructor calls fun() which prints " Base Function".
pls correct me if i m wrong On Mon, Aug 1, 2011 at 9:37 AM, sivaviknesh s <sivavikne...@gmail.com>wrote: > > #include<iostream> > #include<stdio.h> > > using namespace std; > > class Base > { > public: > Base() > { > fun(); //note: fun() is virtual > } > virtual void fun() > { > cout<<"\nBase Function"; > } > }; > > class Derived: public Base > { > public: > Derived(){} > virtual void fun() > { > cout<<"\nDerived Function"; > } > }; > > int main() > { > Base* pBase = new Derived(); > delete pBase; > > getchar(); > return 0; > } > > Output: > *Base Function* > > See following excerpt from C++ > standard<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf>for > explanation. > > *When a virtual function is called directly or indirectly from a > constructor (including from the mem-initializer for a data member) or from a > destructor, and the object to which the call applies is the object under > construction or destruction, the function called is the one defined in the > constructor or destructor’s own class or in one of its bases, but not a > function overriding it in a class derived from the constructor or > destructor’s class, or overriding it in one of the other base classes of the > most derived object.* > > Because of this difference in behavior, it is recommended that object’s > virtual function is not invoked while it is being constructed or destroyed. > See this > <https://www.securecoding.cert.org/confluence/display/cplusplus/OOP30-CPP.+Do+not+invoke+virtual+functions+from+constructors+or+destructors>for > more details. > ..............CAN ANYONE GIVE A SIMPLE EXPLANANTION?? given explanation is > quite confusing.... > > -- > Regards, > $iva > > -- > You received this message because you are subscribed to the Google Groups > "Algorithm Geeks" group. > To post to this group, send email to algogeeks@googlegroups.com. > To unsubscribe from this group, send email to > algogeeks+unsubscr...@googlegroups.com. > For more options, visit this group at > http://groups.google.com/group/algogeeks?hl=en. > -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algogeeks@googlegroups.com. To unsubscribe from this group, send email to algogeeks+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.