Class pointers in C ++ point to arrays of inherited classes

Source: Internet
Author: User

 

Colleagues encountered the following problem in debug:

 1    Class  Basic  2   {  3       Public  :  4 Basic () {cout < "  Basic ctor  " < Endl ;}  5           Virtual ~ Basic () {cout < "  Basic dtor  " < Endl ;}  6            Virtual   Void Foo () {cout < "  Basic foo  " < Endl ;}
PRIVATE:
Char data [4]; 7 }; 8 9 10 Class Deride: Public Basic 11 { 12 Public : 13 Deride () {cout < " Deride ctor " < Endl ;} 14 Virtual ~ Deride () {cout < " Deride dtor " < Endl ;} 15 Virtual Void Foo () {cout < " Deride foo " < Endl ;}
PRIVATE:
Char data [6]; 16 }; 17 18 19 Int Main () 20 { 21 22 Basic * pb = New Deride [ 20 ]; 23 24 Pb [ 1 ]. Foo ();// Correct? 25 26 Delete [] Pb; // is it correct? 27 28 Return 0 ; 29 }

 

The above two calls are problematic for the following reasons:

Pb [1]. Foo () includes the following aspects:

1) Pb [1] = * (Pb + sizeof (basic ));

PB actually points to the deride type memory, if sizeof (basic )! = Sizeof (deride), the Access Method of Pb [1] is not correct in deride [10.

2) Pb [1]. Foo (), Foo () is virtual. To call a function, you need to access the virtual function table.

3) In general, the vptr is put in a fixed position by default, such as the beginning of the class. Therefore, only when the pointer of the current object is obtained correctly can the vptr be obtained correctly.

Based on the above three analyses, we can draw the following conclusions:

1) Pb [1]. Foo ()CodeIs incorrect.

2) Delete [] Pb is also incorrect.

 

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.