Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
1) I know that things initialized with new are on heap. But If we create object of a class without using new in C++,


MyClass obj();


1)Where it is declared,stack or heap??
2) Where it has memory,initializes,stack or heap?
Posted
Updated 26-Jul-11 19:32pm
v3

That object would be created on the stack, and then destroyed on the way out of the function

The Data segment is used for all variables declared outside the scope of any function

The stack is used for all variables declared within a function; in the following example

void afunction()
{
   MyClass *pMyClass=new MyClass();
}

The pointer is local to the function (on the stack) but the class is on the heap
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-Jul-11 12:39pm    
My 4. More exactly, the instance of the class (object of the class type) in on the heap. Some do not understand, so the note is not redundant.
--SA
ahsanriaz1K 27-Jul-11 0:27am    
@barneyman: OK, I know MyClass obj();
will be declared on stack but memory assigned to it cannot be in stack. As class objects are reference type and reference type variables have memory on heap not stack, so how this MyClass obj();
instance has its memory on stack.
Emilio Garavaglia 27-Jul-11 4:38am    
There is no concept of "reference type" and "value type" in C++.
struct and class are the same (except for public vs private default member visibility)
barneyman 27-Jul-11 2:32am    
unless your object explicitly, internall allocates memory from the heap with a new or a malloc call, the stack will be extended by the size of your object when the function SP/BP code kicks in

Try it in the debugger, look at the memory block at &obj, then look at the memory at ESP
You have to be aware that in C++ MyClass obj(); would be a declaration of a function named obj that returns an object of type MyClass.

To actually create an object on the stack, you will have to remove the parenthesis and write:

void someFunction()
{
  MyClass obj; // object on the stack
}
 
Share this answer
 
Comments
ahsanriaz1K 27-Jul-11 0:30am    
We can declare object using MyClass obj();, it is not a function declration, and please tell me that if we will assign memory to obj in someFunction, where does this memory goes? heap or stack?

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