Difference Between Structures and Classes

Introduction

C++ में structure और class दोनों ही user-defined data types होते हैं, जिनका उपयोग data को व्यवस्थित रूप से रखने के लिए किया जाता है। प्रारंभिक स्तर पर ये दोनों काफी समान दिखाई देते हैं क्योंकि दोनों में data members और member functions हो सकते हैं।

लेकिन Object Oriented Programming के संदर्भ में class का उपयोग अधिक किया जाता है क्योंकि यह data security, encapsulation और abstraction जैसे features को बेहतर तरीके से support करती है। वहीं structure का उपयोग सामान्यतः simple data grouping के लिए किया जाता है।

इसलिए इन दोनों के बीच अंतर को समझना आवश्यक है।

Definition of Structure

Structure एक user-defined data type है जिसका उपयोग related data को एक साथ group करने के लिए किया जाता है। यह मुख्य रूप से data storage के लिए उपयोग होता है।

Definition of Class

Class एक user-defined data type है जो data और functions दोनों को एक साथ bind करता है और Object Oriented Programming के concepts को लागू करने में उपयोग होता है।

Syntax Difference

Structure

struct Student {
string name;
int age;
};

Class

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

Structure और Class में अंतर

आधारStructureClass
Default Accesspublicprivate
PurposeData groupingData + Behavior
Securityकमअधिक
OOP Supportसीमितपूर्ण
UseSimple data storageComplex applications
Encapsulationनहीं के बराबरउपलब्ध
InheritanceLimited supportFull support

Default Access का उदाहरण

Structure में default public होता है

#include <iostream>
using namespace std;

struct Student {
string name;
};

int main() {
Student s1;
s1.name = "Rahul"; // allowed
cout << s1.name;

return 0;
}

Output:

Rahul

Class में default private होता है

#include <iostream>
using namespace std;

class Student {
string name;
};

int main() {
Student s1;
s1.name = "Rahul"; // error

return 0;
}

Output:

Error: 'name' is private

उपयोग के आधार पर अंतर

  • Structure का उपयोग तब किया जाता है जब केवल data को group करना हो
  • Class का उपयोग तब किया जाता है जब data के साथ functions भी define करने हों

निष्कर्ष

Structure और Class दोनों ही user-defined data types हैं, लेकिन class अधिक शक्तिशाली होती है क्योंकि यह OOP के सभी features को support करती है। Structure का उपयोग सरल data grouping के लिए किया जाता है, जबकि class का उपयोग complex और secure applications बनाने के लिए किया जाता है।

Leave a Comment

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

Scroll to Top