Microsoft Interview Question
Applications DevelopersCountry: India
Interview Type: In-Person
Reference types are always allocated on the heap - class, interface, delegate, object, string.
Value types (e.g. struct) and pointers are allocated depending on where they are declared. If declared within a method body, then they go on the stack. If declared outisde a method, e.g. as class variables, then they go on the heap.
That's not right. In C++, if you make a class by value (i.e. MyClass m; ), it will be allocated on the stack.
I should have mentioned C# for my case though I believe C++ is the same. When you do "MyClass m" within a method, you are just declaring a pointer, not allocating memory on the heap like with "new".
That's absolutely not true. In C++, when you say MyClass m; you are making a new object (calling the zero-argument constructor) that will be stored on the stack. A full object is created -- not just a pointer! That's how C++ works. If you wanted to make a pointer, you'd have to say MyClass* m;
The OP of this question has said it's a C++ question.
Also, please read this post called "The stack is an implementation detail". I see this sort of misconception all the time. Whether something is placed on the stack or heap isn't really determined by its type:
blogs DOT msdn DOT com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
I don't believe there's any difference between how structs and classes are laid out in C++. Generally, people don't use inheritance for structs, so there will probably be no virtual table pointer, but whether to use inheritance or not is completely up to the programmer. See this StackOverflow thread: stackoverflow DOT com/questions/979211/struct-inheritance-in-c
- eugene.yarovoi September 10, 2012Classes and objects are completely different things (objects have instance variables, pointers to vtables, etc. while classes have class variables and the actual vtables).