ooppointersobjectreference

Why do variables store reference to objects and not the object itself?


I am not new to OOP but never quite understood why variables can't EVER hold the entire object (like in c++, java and php). So what is the advantage of working with pointers all the time as a rule?

thank you, i'm just trying to learn here...


Solution

  • It comes down to automatic vs manual memory management. Platforms like Java and .NET run atop a virtual machine which implements a garbage collector. This automatically manages allocation and destruction of memory. In these systems, all variables derive from a single, base Object type.

    C++ does allow you to have an object-instance stored on the stack (ie, not allocated by pointer and on the heap). C++, by contrast, has many primitive types (int, float, etc) which do not extend a base type.