Objects as Variables of Class Data Type

Introduction

Object Oriented Programming में Class केवल एक structure या blueprint होती है, जबकि actual काम objects के माध्यम से होता है। जब हम किसी class को define करते हैं, तो वह केवल यह बताती है कि data और functions कैसे होंगे, लेकिन वह स्वयं memory में जगह नहीं लेती।

Memory का allocation तब होता है जब हम उस class के objects बनाते हैं। इस दृष्टिकोण से देखा जाए तो object वास्तव में class type का एक variable होता है, जो class के data और functions को उपयोग करने की क्षमता रखता है।

Definition

जब किसी class का object बनाया जाता है, तो वह उस class के data type का एक variable होता है।
अर्थात, जिस प्रकार int, float आदि data types के variables होते हैं, उसी प्रकार class भी एक data type की तरह काम करती है और उसके objects variables के रूप में उपयोग किए जाते हैं।

समझने का तरीका

मान लीजिए:

  • int x; → यहाँ x एक integer variable है
  • उसी प्रकार
  • Student s1; → यहाँ s1, Student class का variable (object) है

इससे स्पष्ट होता है कि object, class data type का variable होता है।

Class Data Type का अर्थ

जब हम class define करते हैं, तो हम एक नया data type बनाते हैं।

उदाहरण:

class Student {
public:
string name;
int age;
};

यहाँ Student एक नया data type बन गया।

अब हम इस data type के variables (objects) बना सकते हैं।

Object Declaration

Class के object को declare करने का सामान्य तरीका:

ClassName objectName;

उदाहरण:

Student s1;
Student s2;

यहाँ s1 और s2, Student class के variables हैं।

Memory Allocation

जब object बनाया जाता है, तब:

  • Data members के लिए memory allocate होती है
  • Member functions के लिए अलग से memory नहीं बनती (वे shared होती हैं)

हर object का data अलग-अलग memory में store होता है।

C++ में उदाहरण

#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;

void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

int main() {
Student s1, s2; // objects as variables

s1.name = "Rahul";
s1.age = 20;

s2.name = "Amit";
s2.age = 22;

s1.display();
s2.display();

return 0;
}

Output:

Name: Rahul
Age: 20
Name: Amit
Age: 22

महत्वपूर्ण बिंदु

  • Class एक user-defined data type होती है
  • Object उस data type का variable होता है
  • हर object का data अलग-अलग होता है
  • Objects के माध्यम से ही class के members को access किया जाता है

निष्कर्ष

Object को class data type का variable माना जाता है क्योंकि class एक नया data type बनाती है और उसके objects उसी type के variables की तरह कार्य करते हैं। यही concept OOP में data organization और program execution का आधार बनाता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top