Professional Documents
Culture Documents
Pointers to class member functions and member variables are used just like pointers to
normal variables and functions.
To 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;
a pointer of class type is declared which points to class's object. Data members and member
functions are accessed using pointer name with arrow -> symbol.
For accessing normal data members the dot . operator is used with object. But when a pointer to
data member means have to dereference that pointer to get what its pointing to, hence it
becomes,
Object.*pointerToMember
ObjectPointer->*pointerToMember
1|Page
Example
class Data
{
public:
int a;
void print() { cout << "a is "<< a; }
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
Output :
a is 10 a is 20
Syntax :
class Data
{ public:
int f (float) { return 1; }
};
int main(0
{
fp2 = &Data::f; // Assignment inside main()
}
C++ allows to have pointers to objects. The pointers pointing to objects are referred to as Object
Pointers.
2|Page
C++ Declaration and Use of Object Pointers
Just like other pointers, the object pointers are declared by placing in front of a object pointer's
name. It takes the following general form :
class-name ∗ object-pointer ;
where class-name is the name of an already defined class and object-pointer is the pointer to an
object of this class type. For example, to declare optr as an object pointer of Sample class type,
we shall write
Sample ∗optr ;
where Sample is already defined class. When accessing members of a class using an object
pointer, the arrow operator (->) is used instead of dot operator.
To access public members using an object the dot operator is used and to access public members using
an object pointer the arrow operator is used.
3|Page