Value And Reference Type In OOPS

OOP Concepts

In my last article, OOP Concepts, I discussed some basics of the OOP including class, object and three other key concepts; i.e., encapsulation, polymorphism, and inheritence.

In this article, we'll discuss another major concept of Value Type and Reference Type. But before moving onto that, we must know about two other things, Stack and Heap. These are data structures in the memory.

Stack can be considered as a linear data structure and represented as physical stack or pile, while heap is a tree-based data structure.

The logical difference between them is that Stack is used for static memory allocation while Heap is used for the dynamic memory allocation. But, both are stored in the computer's RAM.

Now that you've understood these data structures, lets see what Value and Reference types are. Both of these are categories in which data types are divided based on two factors.

If the variable of any data type stores its own data, it falls in Value type category. If it points towards the data, then it belongs to Reference type.

Simple enough? Let's dig out more details.

A value type stores its content on stack. If you assign a value type variable to another variable, the data is copied and both variables work independently. Data types that fall in Value Type category are all predefined data types, structures and enums. The major drawback of Value type is that it is stored on stack and the garbage collector can't access them.

Reference types point towards the data and does not hold the data itself. That's why assigning a reference variable to another variable doesn't copy the data, but just makes another reference variable which points towards the same data at Heap memory, because if it's on heap, the garbage collector can access them. Example of reference types are classes, objects, arrays, etc.

In the next article, I'll try to explain more concepts in some easy ways, so that you can get along quickly. Have any questions? Don't hesitate to comment.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now