[C ++ Basics] 047 _ Why can't constructors be virtual functions?

Source: Internet
Author: User

The topic of this article is that the constructor cannot be a virtual function. First, you do not need to use your mind to remember it, because when you write a virtual constructor, the compiler can check it. The purpose of this article is why constructor cannot be a virtual function.

First, let's take a look at a piece of wrong code. The following code does not pass through the compilation phase.

1 class A {2 public: 3 Virtual A () {4 This-> value = 0; 5} 6 private: 7 int value; 8 };

Why cannot constructors be virtual functions? Here you need to know a concept, that is, virtual function table vtbl. Each class with virtual member functions has a pointer to the virtual function table. Objects use the virtual function address stored in the virtual function table to call virtual functions.

When is the virtual function table pointer initialized? Of course, it is a constructor. When we create an object through new, the first step is to apply for the required memory, and the second step is to call the constructor. Imagine that if the constructor is a virtual function, you must use vtbl to find the entry address of the virtual constructor. Obviously, the memory we applied for has not been initialized, and vtbl is not available. Therefore, the constructor cannot be a virtual function.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.