0

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...

fabio
  • 2,269
  • 5
  • 22
  • 34
  • 4
    Variables in C++ *can* hold entire objects. Variables in Java cannot. Variables in C# can hold objects only if their class inherits from `System.ValueType`. – cdhowie Dec 06 '10 at 19:01

4 Answers4

4

This isn't a requirement of OOP. It is just more efficient to store a reference to some types rather than the contents themself. It can be very cumbersome to pass around complex objects, but highly efficient to just pass a reference or address of the object. Most programming languages support both (value and reference types) of these concepts (the creators of Java choose to have everything inherit from a object).

Many platforms, like .NET, provide structs which are kind of like light-weight objects. They don't support inheritance, but can have fairly complex structures with many members. Even though structs support complex data types, they are value types. Of course, if a struct is too complex it becomes inefficient and then you are better off making it a class.

Jim Anderson
  • 3,602
  • 2
  • 24
  • 21
2

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.

Courtney Christensen
  • 9,165
  • 5
  • 47
  • 56
  • zourtney said: "In these systems, all variables derive from a single, base Object type." This can be confusing. In .NET, even though value types ultimately inherit from Object, their contents are stored on the stack rather than a "reference." – Jim Anderson Dec 06 '10 at 19:40
1

The point is memory management; by using pointers, your program doesn't always make a copy of variable it just points to it.

Why C Pointers

0

The ability for primitive values to be stored directly as values and for objects to be stored as references was a conscious decision made by the developers of Java.

Apart from the other beneficial answers provided, it should be noted that references actually allow values and associated behaviours to be bundled together with other useful information... Such as the information that can assist in the creation of an object instance.

Please refer to some of the information provided here.

Grateful
  • 9,685
  • 10
  • 45
  • 77