CPP Program To Implement Classes with Pointers as Data Members

Aim:

To implement classes with pointers as data members

Pointers to Class Members in C++

Just like pointers to normal variables and functions, we can have pointers to class member functions and member variable

Defining a Pointer of Class type

We can define pointer of class type, which can be used to point to class objects.

Class Simple
{
    Public:
    int a;
};

int main()
{
    Simple obj;
    Simple* ptr;   // Pointer of class type
    ptr = &obj;
 
    cout << obj.a;
    cout << ptr->a;  // Accessing member with pointer
}
Code language: PHP (php)

Here you can see that we have declared a pointer of class type which points to class’s object. We can access data members and member functions using pointer name with an arrow -> symbol.

Pointer to Data Members of Class

We can use a pointer to point to the class’s data members (Member variables).

The syntax for Declaration:

datatype class_name :: *pointer_name;

The syntax for Assignment:

pointer_name = &class_name :: datamember_name;

Both declaration and assignment can be done in a single statement too.

datatype class_name::*pointer_name = &class_name::datamember_name ;

Using Pointers with Objects

  • For accessing normal data members we use the dot . operator with object and -> qith pointer to object.
  • But when we have a pointer to data member, we have to dereference that pointer to get what it’s pointing to, hence it becomes,
Object.*pointerToMember

and with a pointer to object, it can be accessed by writing,

ObjectPointer->*pointerToMember

Some Points to Remember

  1. You can change the value and behaviour of these pointers on runtime. That means, you can point it to other member function or member variable.
  2. To have pointer to data member and member functions you need to make them public.

Algorithm:

  1. Create a class called data
  2. Define a function called print and print the variable called a
  3. Declare a pointer to object in main function
  4. To declare a pointer to data member dereference the pointer to what its point to.
  5. 5.display the result

Program:

#include<iostream>
using namespace std;
class data
{
private:
int a;
int* p=&a;
public:
void getdata()
{
cout<<"ENTER DATA :"<<endl;
cin>>a;
}  
void print()
{
cout<<"DATA :"<<*p;
}
};
int main()
{
data A,*a;
a=&A;
a->getdata();
a->print();
return 0;
}

Execution:

INPUT :
ENTER DATA: 7

OUTPUT :
DATA: 7

Result:

Thus, the Implementation Classes with Pointers as Data Members were executed successfully.

Leave a Comment