Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
Let's say we have a class A
class A 
{
// blabla
public int x;
}


when we do this:
A a=new A();

is the x also allocated dynamically?
An explanation will be great. Thank you

What I have tried:

I think it is done dynamically since we need to go threw the object to access "x".
Posted
Updated 24-Aug-18 2:18am
v4

Only the non-static member variables are stored within the allocated memory block. With your example the memory holds only the x member and has therefore at least the size of an int.

You can verify this by printing out the addresses:
class A
{
public:
    A() { x = 0; }
    int x;
};

int main()
{
    A *a = new A();
    printf("Size of A = %lu\n", sizeof(*a));
    printf("Address of a = %p\n", a);
    printf("Address of a->x = %p\n", &a->x);
    return 0;
}
which might print
Size of A = 4
Address of a = 0x602010
Address of a->x = 0x602010

Note also the correct syntax used in my example (class definition must be terminated with a semicolon and a is a pointer).
 
Share this answer
 
v2
Comments
amine zawix 24-Aug-18 8:22am    
Thank you
You can create object on the stack or dynamically on the heap.
On the stack:

C++
void myFunc()
{
   A a;
}


Now exists the "a" as long as you execute the myFunc.

Dynamically on heap:

A* heapA = new A();


Now you have a pointer to A and can use it as long as you need it.
After that you need to destroy it in order to get the memory free:
delete heapA;


I hope that answers your question. For more details take a look at Strategies for the Allocation of Memory - ModernesCpp.com[^]
 
Share this answer
 
v3
Comments
amine zawix 24-Aug-18 8:22am    
Thank you

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