Memory model for C + + class objects

Source: Internet
Author: User
Tags inheritance

C + + Class object memory structure

First, we introduce the layout of class object memory in C + + with inheritance relationship: in C + +, if there is a virtual function in a class, then it has a pointer __vfptr of the virtual function table in the first memory data of the class object. The memory data for the member variables in the class is followed by.

For subclasses, the first memory data records the copy of the parent class object (including the parent class virtual function table pointer and the member variable). The following is the subclass's own member variable data.

The same principle is true for subclasses of subclasses. However, no matter how many subclasses are inherited, there is always only one virtual function table pointer in the object.

To explore the memory layout of C + + class objects, write several classes and functions first

First write a base class:

class Base
{
public:
virtual void f() { cout << "Base::f" << endl; }
virtual void g() { cout << "Base::g" << endl; }
virtual void h() { cout << "Base::h" << endl; }
int base;
protected:
private:
};

Then, we study the memory object structure of subclasses in a variety of different inheritance situations.

1. No virtual function set inheritance

//子类1,无虚函数重载
class Child1 : public Base
{
public:
virtual void f1() { cout << "Child1::f1" << endl; }
virtual void g1() { cout << "Child1::g1" << endl; }
virtual void h1() { cout << "Child1::h1" << endl; }
int child1;
protected:
private:
};

This subclass Child1 does not inherit a virtual function of any of the base classes, so its virtual function table is as follows:

We can see that in the virtual function table of subclasses, the virtual function of the base class is stored first, and the virtual function of the subclass is stored.

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.