Pointers to Classes & Class Members

Introduction

C++ में pointers का उपयोग memory address को store करने और dynamic memory management के लिए किया जाता है। जब हम Object Oriented Programming में classes और objects के साथ काम करते हैं, तब pointers का उपयोग objects और उनके members को access करने के लिए भी किया जाता है।

Pointers के माध्यम से हम class objects को efficiently handle कर सकते हैं और dynamic allocation, polymorphism तथा advanced programming techniques को implement कर सकते हैं।


Definition

Pointer to Class

Pointer to class वह pointer होता है जो किसी class के object का address store करता है।


Pointer to Class Members

Pointer to class members वह pointer होता है जो class के data member या member function को point करता है।


Pointer to Object का Syntax

ClassName *pointerName;

Example (Pointer to Object)

#include <iostream>
using namespace std;

class Demo {
public:
int x;

void show() {
cout << "Value: " << x;
}
};

int main() {
Demo d1;
Demo *ptr;

ptr = &d1; // pointer stores address

ptr->x = 50;
ptr->show();

return 0;
}

Output:

Value: 50

Working को समझना

  • ptr object d1 का address store करता है
  • ptr->x → data member access
  • ptr->show() → function call

Pointer to Data Member

Syntax

dataType ClassName::*ptrName;

Example

#include <iostream>
using namespace std;

class Demo {
public:
int x;
};

int main() {
Demo d1;

int Demo::*ptr = &Demo::x;

d1.*ptr = 100;

cout << d1.x;

return 0;
}

Output:

100

Pointer to Member Function

Syntax

returnType (ClassName::*ptrName)();

Example

#include <iostream>
using namespace std;class Demo {
public:
void show() {
cout << "Hello";
}
};int main() {
Demo d1; void (Demo::*ptr)() = &Demo::show; (d1.*ptr)(); return 0;
}

Output:

Hello

Important Operators

  • -> → pointer से member access
  • .* → object के साथ member pointer access
  • ->* → pointer के साथ member pointer access

Advantages

  • Dynamic memory handling में उपयोगी
  • Efficient object access
  • Polymorphism में उपयोग
  • Flexible programming

निष्कर्ष

Pointers to classes और class members C++ में advanced programming के लिए महत्वपूर्ण concept हैं। इनके माध्यम से हम objects और उनके members को efficiently access कर सकते हैं और complex operations को आसानी से implement कर सकते हैं।

Leave a Comment

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

Scroll to Top