Disassembly Quest C + + inheritance

Source: Internet
Author: User

#include <iostream>classtabletennisplayer{Private:    intID; Public: Tabletennisplayer (intID); voidsayhi ();}; Tabletennisplayer::tabletennisplayer (intN) {ID=N;}voidTabletennisplayer::sayhi () {std::cout<<"hi,i am Player"<< ID <<Std::endl;}classMasterplayer: Publictabletennisplayer{Private:    intID; Public: Masterplayer (intID); voidfuck ();}; Masterplayer::masterplayer (intN): Tabletennisplayer (n) {ID=N;}voidMasterplayer::fuck () {std::cout<<"Fuck"<<Std::endl;}intMainvoid){    usingstd::cout; usingstd::cin; Tabletennisplayer player (1); Masterplayer Master (2);    Player.sayhi ();    Master.sayhi ();    Master.fuck (); cout<<sizeof(player) <<Std::endl; cout<<sizeof(master) <<Std::endl; Cin.Get();}

The parent class member variable ID is initialized in the constructor.

Subclasses also have member variable IDs, which are initialized in the subclass constructor.

The disassembly code sees that the subclass constructor initializes the subclass when the parent class constructor is called first to initialize the parent class--specifically to initialize the parent class member variable.

So:

This is the parent class in memory storage 00 00 00 01 of 4 bytes

This is the storage of the subclass in the parent class:

00 00 00 02 00 00 00 02 is 8 bytes, the first four bytes are the parent class member variable, and the last four bytes is the subclass member variable

As a result, subclasses are inclusive relationships to the parent class. This refers to the inclusion of a parent class member variable. In addition, the constructor is nothing special. is actually the function that is called automatically when the class is established. To initialize a class member, that is, to request memory for a member variable. Subclass initialization, first calling the parent class constructor method, initializes the parent class member variable. Then call your own, initialize your own member variable.

Disassembly Quest C + + inheritance

Related Article

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.