Written by Sai Sandeep Thota on February 4, 2013 in C++ > Programming

Pointers to Class Members in C++

GET ALERTS:

Get our Latest updates delivered to your mailbox!

C++ allows a special type of pointer which points to a member of a class. This type of pointer is know as pointer to a class member. This is not any normal C++ pointer, it provides the offset into an object of the member class at which that member can be found. We can access member of a class with special pointer to member operators .*, ->*.

In the main function, int pointer::*data; points to class variables and int (pointer::*fun)(); points to a function. In the later steps we have made data to point to x variable and fun to pointer to square function. The below is a sample program to get a basic knowledge about Pointers to class members.

#include<iostream.h>
#include<conio.h>

class pointer {
	public:
	int x;
	pointer(int);
	int square();
};

pointer::pointer(int i) {
	x=i;
}

int pointer::square() {
	return (x*x);
}

void main() {
	pointer ob1(20), ob2(40);
	int pointer::*data;
	int (pointer::*fun)();
	clrscr();
	data=&pointer::x;
	fun=&pointer::square;
	cout<<"\nOb1.X Value:"<<ob1.*data;
	cout<<"\nOb2.X Value:"<<ob2.*data;
	cout<<"\nSquare of Ob1.X Value:"<<(ob1.*fun)();
	cout<<"\nSquare of Ob2.X Value:"<<(ob2.*fun)();
	getch();
}

Output:
pointers-to-class-members

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: