In C# classes are stored in heap, and structs are stored in stack.
Does in C++ classes and strucs are stored in the same way (assuming I create my classes and structs statically, and every member of class or struct is not allocated by new) ?
Please explain this using snippet of code below:
class B
{
int b;
}
class C
{
int c;
}
class A
{
B b;
C c;
int x;
}
struct SB
{
int sb;
}
struct SC
{
int sc;
}
struct SA
{
SB sb;
SC sc;
int x;
}
void main()
{
A a1;
A *a2 = new A;
SA sa1;
SA *sa2 = new SA;
}
There is no (necessary) difference in how structs are stored vs. how classes are stored. In fact, the only difference between structs and classes in C++ is that struct members are public by default, and class members are private by default.
Like any other kind of object, an object of class or struct type has a storage duration which is determined by how it's created.
An object declared inside a function has its lifetime limited to the enclosing block; this is typically implemented by storing it on the stack.
An object declared outside a function, or with the static
keyword, has a lifetime that extends over the entire execution of the program; this might be implemented by storing it in the data segment.
An object allocated by a new
operator (or malloc()
call) exists until it's delete
d (or free()
ed); such objects are allocated in the "free store", sometimes informally referred to as "the heap".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With