A constructor cannot be virtual

后端 未结 2 1703
孤街浪徒
孤街浪徒 2021-02-10 06:04

In one of the C++ tutorials in internet, i found out the below description on why a constructor cannot be virtual

We cannot declare a virtual constructor

2条回答
  •  长情又很酷
    2021-02-10 06:36

    The constructor cannot be virtual because the standard says so.

    The standard says so because it wouldn't make sense. What would a virtual constructor do?

    Virtual methods are used in polymorphism... how should polymorphism work if you don't even have the objects yet?

    We should specify the exact type of the object at compile time, so that the compiler can allocate memory for that specific type.

    We should specify the exact type at compile time because we want an object of that type... I found their description very confusing too.

    Also, in the paragraph it doesn't say this is the reason why constructors can't be virtual. It explains why virtual methods shouldn't be called from the constructor, but that's about it.

提交回复
热议问题