Advertisement
mbazs

C++ virtual fn call during base ctor

Nov 2nd, 2019
512
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct Base {
  4.     Base() { std::cout << "in Base ctor "; f(); }
  5.     virtual void f() { std::cout << "Base::f() is called" << std::endl; }
  6.     virtual ~Base() {}
  7. };
  8.  
  9. struct Derived: public Base {
  10.     Derived() : Base() { std::cout << "in Derived ctor "; f(); }
  11.     virtual void f() { std::cout << "Derived::f() is called" << std::endl; }
  12.     virtual ~Derived() {}
  13. };
  14.  
  15. int main()
  16. {
  17.     Base *d = new Derived; // during construction: there is no polymorphism
  18.     /*
  19.      * Prints:
  20.      * in Base ctor Base::f() is called
  21.      * in Derived ctor Derived::f() is called
  22.      */
  23.  
  24.     d->f(); // during normal member function call: polymorphism works
  25.     /* Prints:
  26.      * Derived::f() is called
  27.      */
  28.     delete d;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement