Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends!

I want to know that:
When we declare the objects of an class,where an how much memory will be allocated by object of that class.

Ex:
C++
class A
{
  public : display()
  {
  int v = 10;
  cout<<"\nv:"<<v;
  }
}
main()
{

A  a1;  //hw much & where a1 allocates memmory.
A *aptr;//hw much & where a1 allocates memmory.

getch();
}
Posted
Updated 30-Sep-10 2:35am
v3

'How much memory' is given by sizeof operator[^].

The following, compiler-friendly version of your program
C++
class A
{
  public :
  void display()
  {
    int v = 10;
    std::cout<<"\nv:"<<v;
  }
};
int main()
{
  A  a1;  //hw much & where a1 allocates memmory.
  A *aptr;//hw much & where a1 allocates memmory.
  std::cout << "sizeof(a1)= " << sizeof(a1) << std::endl;
  std::cout << "sizeof(aptr)= " << sizeof(aptr) << std::endl;
}


produces the output below:
sizeof(a1)= 1
sizeof(aptr)= 4


We get sizeof(a1)=1 because the class is empty (i.e. has no data), but, anyway a C++ object must have size > 0 (must have an identity, see Stroustrup's "Why is the size of an empty class not zero?"[^]).

We get sizeof(aptr)=4 because the program doesn't allocate an object, it allocates just 'a pointer to an object' (pointing to garbage) and pointers are 4-bytes wide on my 32-bits system.


Both allocations happens on the stack.
:)
 
Share this answer
 
v4
// A a1;
+ The memory is on-stack =sizeof(A)
+ The on-heap memory, allocated dynamically
-> by the class constructor (optional)
-> by the class constructors of the in-class embedded objects (optional)
-> by the classes from which A is derived (optional)

// A* aptr;
+ The memory is on-stack =sizeof(INT_PTR)

// A* aptr = new A;
+ The memory that holds aptr is on-stack sizeof(INT_PTR)
+ The on-heap memory, allocated dynamically=sizeof(A)
-> by the class constructor (optional)
-> by the class constructors of the in-class embedded objects (optional)
-> by the classes from which A is derived (optional)


:)
 
Share this answer
 
v3
Comments
Eugen Podsypalnikov 30-Sep-10 8:35am    
Thank you, Sauro ! :)

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