Introduction
C++ में कई बार ऐसे objects बनाए जाते हैं जिनकी values को program के दौरान बदलना नहीं होता। ऐसे objects को constant objects कहा जाता है। यह concept data को सुरक्षित और स्थिर (unchanged) रखने में मदद करता है।
इसी के साथ, जब किसी class के member functions को इस प्रकार define किया जाता है कि वे object के data को modify न करें, तो उन्हें constant member functions कहा जाता है। यह दोनों concepts program में data integrity बनाए रखने के लिए उपयोगी होते हैं।
Definition
Constant Object
Constant object वह object होता है जिसे const keyword के साथ declare किया जाता है और जिसके data members को program के दौरान modify नहीं किया जा सकता।
Constant Member Function
Constant member function वह function होता है जो object के data members को modify नहीं करता और इसे function के अंत में const keyword लगाकर define किया जाता है।
Constant Object का Syntax
const ClassName objectName;
Constant Member Function का Syntax
returnType functionName() const {
// function body
}
Constant Object का उदाहरण
#include <iostream>
using namespace std;
class Demo {
public:
int x = 10;
};
int main() {
const Demo d1;
// d1.x = 20; // not allowed
cout << d1.x;
return 0;
}
Output:
10
Constant Member Function का उदाहरण
#include <iostream>
using namespace std;
class Demo {
public:
int x = 50;
void display() const {
cout << "Value: " << x;
}
};int main() {
const Demo d1;
d1.display(); // allowed
return 0;
}
Output:
Value: 50
Working को समझना
const Demo d1;→ constant object बनाया गया- data members को modify नहीं किया जा सकता
- केवल const member functions ही call किए जा सकते हैं
- non-const functions call नहीं होंगे
Important Rules
- Constant object केवल constant member functions को call कर सकता है
- Constant member function data members को modify नहीं कर सकता
- Function के अंत में
constलगाना आवश्यक है
Error Example
class Demo {
public:
int x;
void setValue() {
x = 10;
}
};
int main() {
const Demo d1;
d1.setValue(); // error
}
Output:
Error: cannot call non-const function on const object
निष्कर्ष
Constant objects और constant member functions data को सुरक्षित और स्थिर बनाए रखने में महत्वपूर्ण भूमिका निभाते हैं। यह सुनिश्चित करते हैं कि object की values अनजाने में modify न हों और program अधिक reliable बने।