Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have created a class with 2 methods(but no data members). when I checked the size of the object which created on stack its says 1. But when I checked for the object created on heap, it says 4. why it is different?

What I have tried:

class MyClass
{
public:
    void print()
    {
        cout << "print";
    }
    void print2()
    {
        cout << "print2";
    }
private:
    //bool bT;
    //int data;
    //int data2;
};

int main()
{
    MyClass stackObj;
    MyClass* heapObj = new MyClass();

    int classSize = sizeof(MyClass); /// outputs 1
    int stackObjsize = sizeof(stackObj); /// outputs 1
    int heapObjsize = sizeof(heapObj); /// outputs 4. why?
    return 0;
}
Posted
Updated 28-Jul-19 21:23pm

1 solution

Because heapObj isn't a MyClass instance, it's a pointer to a MyClass instance - and sizeof is returning the size of the pointer, not the underlying object.
 
Share this answer
 
Comments
Rajeesh_R 29-Jul-19 3:29am    
Thanks.! now I understood.

after i changed

int heapObjsize = sizeof(*heapObj); /// outputs 1
OriginalGriff 29-Jul-19 3:39am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900