Sizeof size of Class Object

Source: Internet
Author: User

1,

Class cbase
{
Int;
Char
* P;
}; Cout <"sizeof (cbase) =" <sizeof (cbase) <Endl; answer: 82, class cbase
{
};

Run cout <"sizeof (cbase) =" <sizeof (cbase) <Endl;

Sizeof (cbase) = 1; instantiation, the so-called class instantiation is to allocate an address in the memory, each instance has a unique address in the memory. Similarly, empty classes will also be instantiated (do not take the Bean package improperly for dry food, empty classes are also classes), so the compiler will implicitly Add a byte to the empty class, in this way, the unique address is available after the empty class is instantiated. Therefore, the empty sizeof class is 1.

3. After adding a virtual function

Class cbase
{
Public:
Cbase (void );
Virtual
~ Cbase (void );
PRIVATE:
Int;
Char
* P;
};

Run sizeof (cbase) = 12 again. Why? : "When there is a virtual function in the C ++ class, there is a pointer to the virtual function (vptr). In 32-bit systems, the pointer size is 4 bytes."

4. inherit class cChild:
Public cbase
{
Public:
CChild (void );
~ CChild (void );
PRIVATE:
Int B;
};

Run: cout <"sizeof (cChild) =" <sizeof (cChild) <Endl;

Output: sizeof (cChild) = 16;

The subclass size is the size of its member variables plus the subclass size.

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.