简体   繁体   中英

Strange behavior of virtual functions in constructor

I have searched related questions about virtual functions in constructors and I know that if we call virtual functions in constructor in base class, only the base version of virtual is invoked.

However, what I post below shows that the calling of virtual in Base constructor actually calls the virtual version in D2.

I know it may seems kind of duplicated, but I wonder if anyone help me with it.

My Code:

#include<iostream>
struct B
{
  B()=default;
  B(const B& b)  {b.fun();}
  virtual void fun()const  {std::cout<<"virtual_B"<<std::endl;}
};
struct D1:public B
{
  D1()=default;
  D1(const D1& d1):B(d1)  {}
  void fun()const  {std::cout<<"virtual_D1"<<std::endl;}
};
struct D2:public D1
{
  D2()=default;
  D2(const D2& d2):D1(d2)  {}
  void fun()const  {std::cout<<"virtual_D2"<<std::endl;}
};
int main()
{
  D2 a;
  D2 b=a;
  return 0;
}

Because you call b.fun() , b is existing fully constructed object. Virtual methods don't work in virtual fashion if you call them on the this pointer which is not yet fully constructed object. If you call other objects' virtual method on constructor they will totally work as expected.

I know that if we call virtual functions in constructor in base class, only the base version of virtual is invoked.

You have misunderstood that rule.

It does not mean any way of calling the virtual function from within the constructor. It mean calling the virtual function for the object being constructed.

Within the constructor, you called the virtual function for a different (and fully constructed) object whose compile time class was B and runtime class was D2. On that object you get the D2 version of the virtual function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM