Sizeof for a class inheriting a base class with a virtual function

For the next piece of code.

/*This program demonstartes how a virtual table pointer 
 * adds to a size of a class*/

class A{

};

class X{
    public:
        void doNothing(){}
    private:
        char a;

};

class Z:public X {

    public:
        void doNothing(){}
    private:
        char z;

}; 

class Y{
    public:
        virtual void doNothing(){}
    private:
        char a;

};

class P:public Y {

    public:
        void doNothing(){}
    private:
        char pp[4];

};

int main(){
    A a;
    X x;
    Y y;
    Z z;
    P p;
    std::cout << "Size of A:" << sizeof(a) << std::endl;// Prints out 1
    std::cout << "Size of X:" << sizeof(x) << std::endl;//Prints out 1
    std::cout << "Size of Y:" << sizeof(y) << std::endl;//Prints 8
    std::cout << "Size of Z:" << sizeof(z) << std::endl;
//Prints 8 or 12 depending upon wether 4 bytes worth of storrage is used by Z data member.
    std::cout << "Size of P:" << sizeof(p) << std::endl;
    std::cout << "Size of int:" << sizeof(int) << std::endl;
    std::cout << "Size of int*:" << sizeof(int*) << std::endl;
    std::cout << "Size of long*:" << sizeof(long*) << std::endl;
    std::cout << "Size of long:" << sizeof(long) << std::endl;
    return 0;

}

The behavior that I seem to notice is that whenever an instance is created by an empty class or an empty class is inherited from byte boundaries, they are not taken into account (i.e. an object of 1 byte size is allowed), in each other case the size The object seems determined by byte boundaries.

What is the reason? I ask from what point I guess.

+3
source share
2 answers

Stroustrup , . , 1 , , , , .

+3

, , , , sizeof(A)==1, X A, char sizeof(X)==1 ( , 2 - A, char X).

" ". C/++ (ISO ++ 1.8 [intro.object]/5) - , , , 1 . , , . , A 1 , A , , ; X char.

+6

Source: https://habr.com/ru/post/1716623/


All Articles