C++: What is the size of an object of an empty class?

后端 未结 16 1591
悲&欢浪女
悲&欢浪女 2020-11-22 11:54

I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and

16条回答
  •  清酒与你
    2020-11-22 12:36

    #include
    using namespace std;
    
    
        class Empty { };
        int main()
        {
            Empty* e1 = new Empty;
            Empty* e2 = new Empty;
    
            if (e1 == e2)
                cout << "Alas same address of two objects" << endl;
            else
                cout << "Okay it's Fine to have different addresses" << endl;
    
            return 0;
        }
    

    Output: Okay it's Fine to have different addresses

    Returning size 1 ensures that the two objects will not have the same address.

提交回复
热议问题