C + + object model: Single inheritance, multiple inheritance, virtual inheritance

Source: Internet
Author: User

C + + object model

There are two concepts that can explain the C + + object model:

The part of the language that directly supports object-oriented programming.
The underlying implementation mechanism for various support.

Single Inheritance (parent class with virtual function)
 1 #include <iostream> 2 #include <vector> 3 using namespace  std; 4 5 class  Base 6  {7  Public : 8 void Fun1 () {cout << "Base fun1" <<  Endl;} 9 virtual void fun2 () {cout << "Base fun2" <<  Endl;} Private : int  a;12 };13 class Derive:public  Base15  {public : + void fun1 () { cout << "Derive fun1" <<  Endl;} void Fun2 () {cout << "Derive fun2" <<  Endl;} Private : $ int  b;21 };22 int  main ()  { base b;26  Derive d;27 base *p = &  d;28 p->  fun1 (); p->  fun2 (); System ("Pause" ); return 0 ; span>                 

Output: The base class pointer p dynamically binds at run time, Fun2 calls the subclass method, fun1 The parent class method is still called because there is no virtual

Memory model:

The virtual table of the pointer points to the subclass method address

In order to support a polymorphic mechanism, the compiler adds a virtual function pointer (vptr) to the class when a class itself defines a virtual function, or if its parent class has a virtual function. Virtual function pointers are generally placed in the first position of the object's memory layout, in order to ensure that the virtual function table can be taken with maximum efficiency in the case of multi-level inheritance or multiple inheritance.

When VPRT is at the front of the object's memory, the address of the object is the virtual function pointer address.

Virtual inheritance

C + + object model: Single inheritance, multiple inheritance, virtual inheritance

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.