Initializing Member Values

Introduction

जब किसी class का object बनाया जाता है, तब उसके data members (variables) को उचित प्रारंभिक मान (initial values) देना आवश्यक होता है। यदि data members को initialize नहीं किया जाता, तो उनमें garbage values आ सकती हैं, जिससे program का output गलत हो सकता है।

C++ में member values को initialize करने के कई तरीके होते हैं, जैसे constructor के माध्यम से, direct assignment के द्वारा, या initialization list का उपयोग करके। सही initialization program को reliable और predictable बनाता है।

Definition

Initializing Member Values वह प्रक्रिया है जिसमें class के data members को object के creation के समय प्रारंभिक मान (initial values) प्रदान किए जाते हैं।

Member Values Initialize करने के तरीके

1. Direct Assignment

इस method में object बनाने के बाद values assign की जाती हैं।

Example

#include <iostream>
using namespace std;

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

int main() {
Student s1;

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

cout << "Name: " << s1.name << endl;
cout << "Age: " << s1.age;

return 0;
}

Output:

Name: Rahul
Age: 20

2. Constructor के माध्यम से Initialization

इस method में constructor का उपयोग करके object बनाते समय ही values initialize की जाती हैं।

Example

#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;

Student(string n, int a) {
name = n;
age = a;
}
};

int main() {
Student s1("Amit", 22);

cout << "Name: " << s1.name << endl;
cout << "Age: " << s1.age;

return 0;
}

Output:

Name: Amit
Age: 22

3. Initialization List का उपयोग

यह एक advanced और efficient तरीका है जिसमें constructor के साथ initialization list का उपयोग किया जाता है।

Syntax

ClassName(parameters) : member1(value1), member2(value2) {
// body
}

Example

#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;

Student(string n, int a) : name(n), age(a) {
}
};

int main() {
Student s1("Ravi", 21);

cout << "Name: " << s1.name << endl;
cout << "Age: " << s1.age;

return 0;
}

Output:

Name: Ravi
Age: 21

Initialization का महत्व

  • Garbage values से बचाता है
  • Program को predictable बनाता है
  • Code को efficient बनाता है
  • Data को सही प्रारंभिक स्थिति देता है

निष्कर्ष

Initializing Member Values एक महत्वपूर्ण प्रक्रिया है जो यह सुनिश्चित करती है कि object के data members सही और meaningful values के साथ शुरू हों। Constructor और initialization list का उपयोग करके initialization को अधिक प्रभावी और सुरक्षित बनाया जा सकता है।

Leave a Comment

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

Scroll to Top