Does a class have only one pointer?

Source: Internet
Author: User
In C ++, does a class pointer have only one pointer for a class? For example, this pointer. In fact, each base class has a pointer, so that a multi-inheritance and multi-polymorphism inheritance class has multiple this pointers, but if all these class layers are single inheritance, all pointers are the same and point to the starting position of the instance. This pointer is not actually stored in a certain place. It is determined by the compiler during compilation, just like the sizeof operator. We need to know that the value of this pointer used at different levels of the class is not necessarily the same (in the case of polymorphism inheritance ). Instead of just the this pointer, the compiler automatically assigns different values to different pointer types. For example, the following code: Class A {int I ;}; Class B {Int J ;}; Class C: Public A, public B {int K ;}; int main () {C; A * pA = & C; B * pb = & C ;.........} Test results: Pa is not equal to Pb. The value assignment of the visible class pointer is different from the normal variable value assignment. In fact, because the type of a * or B * is not the same as that of & C (C *), there is an automatic type conversion. It is precisely this type conversion that automatically assigns different values to Pa and Pb. In this way, the correctness of the use of the pointer to the arguments class members is ensured. Note that for instances of the same class, the pointers of different types (base classes) are not necessarily the same. This occurs in two cases: one is multi-inheritance, the other is that the base class does not have virtual functions, and the derived class has virtual functions. In both cases, the pointers of the derived class and the base class are different.

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.