0

Is memory allocation for class (when initializing an object) is the same as struct? I know that when we initialize struct,

struct example {
    int a;
    double b; 
    int c;
}

the memory allocated will be = (0-4) int, (8-16) double, (16-20) int. (If I am not mistaken)

What if we want to initialize

class Example {
private:
    int a;
    double b;
    int c;
public:
    Example();
}

Example object();

?

What's the memory allocation behavior when the object is initialized? Is it the same as struct?

Maria Khelli
  • 21
  • 1
  • 4

2 Answers2

0

Yes. Literally the only difference between a class and a struct is that in a struct, member-variables/methods listed in the first section of the declaration (above any public:/protected:/private: lines) are treated as public, whereas in a class they are treated as private.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
0

Ask sizeof. It is always correct. In this simple case, the class is guaranteed to have no hidden members; in general that isn't true.

The rule isn't about class vs struct; the only difference is the default in struct is public members but class is private members. The rule is about when you use expensive things. When you add virtual in, the sizes of things start to change. When you add virtual inheritance, things get a lot bigger.

You can only use RTTI on a class that has a virtual member. See How to get the typeid of a void* pointer? for details.

You have asked a further question; whether you can just add up the sizes of the members. The answer is a definite "No". You can't do that. On my platform, that struct may well take up, 24 bytes due to alignment (the double wants to be 8 byte aligned).

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • Ah, yes. I just tried the sizeof, it turns out both the object from the class and struct are the same (in this case). However, I haven't tried to add a function member, yet, to the class. Might try to do so. For the total memory allocated, it is 24 bytes (same as yours). From my understanding, the int a will be allocated (0-4), empty (4-8), double (8-16), int (16-20), and empty again (20-24). Thank you for your explanations! – Maria Khelli Feb 23 '22 at 02:17
  • @MariaKhelli: Adding a non-virtual member function will make no difference. – Joshua Feb 23 '22 at 02:19