I read the stuff of spicy chicken, and I thought about writing something.

Source: Internet
Author: User

Article 1:

/*
* Conclusion:
* The data of a class object can be reduced (slice), but the virtual table of the class is not affected ).
* The pointer to the virtual table is saved in the data area of the Class Object. This is only the responsibility of the Class Object.
*/
# Include
Using namespace STD;

Class
{
Public:
Void print (){
Cout <"This Is A." < }
};

Class B: public
{
Public:
Void print (){
Cout <"This is B." < }
};

Class Va
{
Public:
Virtual void print (){
Cout <"This Is A." < }
};

Class Vb: Public va
{
Public:
Void print (){
Cout <"This is B." < }
};

Int main (void)
{
A _;
B _ B;
A * _ Pa = & _ A; // a pointer to the _ A object.

// A pointer to the _ B object, but the accessed data size is sizeof ()
A * _ PB = & _ B;

Va _ Va;
VB _ Vb;
VA * _ VPA = & _ Va;

// A pointer to the _ VB object, but the accessed data size is sizeof (VA)
VA * _ VPB = & _ Vb;

_ Pa-> Print ();
_ Pb-> Print ();

_ VPA-> Print ();
_ VPB-> Print ();

Return 0;
}

 

Article 2:

# Include

Using namespace STD;

Class {
Public:
Virtual void fun () {cout <"A: Fun" < Virtual void fun2 () {cout <"A: fun2" < };

Class B: Public {
Public:
Void fun () {cout <"B: Fun" < Void fun2 () {cout <"B: fun2" < };

Int main (void)
{
Void (A: * Fun) (); // defines the function pointer in Class.
A * P = new B;

// The returned index value of the slot in vtbl is irrelevant to A and B.
Fun = & A: Fun; (p-> * Fun) (); // compiler internal computation: p-> (vptr + index )();
/*
* Note: P points to a Class A object, but in vtbl, it is a function pointer of Class B.

* As mentioned above, class objects (data) only maintain vptr. As for the function address, run

* Is calculated based on the index.
*/
Fun = & A: fun2;
(P-> * Fun )();
 
Delete P;

Return 0;
}

Article 3:

Delete P; the compiler maintains and recycles the sizeof (B) size in the internal state, instead of sizeof ().

 

If any, Please master the axe.

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.