Do you know pointers play an important role in programming? Have you ever used a pointer to object in C++? If not, then don’t worry. We will explain how to use it.
In this article, we will learn about pointers. We will discuss about pointer to object in C++. We will make code to understand about accessing member functions with or without pointers clearly. We will also see how we can access member functions using new keyword and arrow operator. So, before moving on to pointer to object in C++, one should know about pointers. You can refer to Introduction to Pointersarticle to learn more about pointers and their types.
Pointers in C++ are the variables that store the address of another variable. Similarly, a pointer to an object is the variable that holds the address of an object. Data members and member functions of an object can be accessed using pointers. There are majorly four types of pointers.
Null pointer: When we assign a NULL value to the pointer, it is called a Null pointer.
Void pointer: A void pointer have no data type associated with it. It can store address of any data type. A void pointer is declared with a void keyword. To print its value it must be typecasted.
Wild pointer: This type of pointer is only declared and not assigned the address of any variable.
Dangling pointer: When a pointer points toward the variable whose memory we have de-allocated, it is known as a Dangling pointer.
Moving forward, let’s understand the syntax of a pointer.
Syntax of a Pointer
The syntax of a pointer in C++ is given below.
int a=3;
int *pointer=&a; // data_type * pointer_name=&variable;
You can also try this code with Online C++ Compiler
It is important to note that the memory of the class is allocated only when it is instantiated or, in other words, when an object is created. We can access member functions using pointers. Make a note to use the bracket, as the dot operator has higher precedence. Whenever we use ‘*’(indirection operator) with our pointer variable then we call it dereferencing of a pointer.
Accessing Member Functions using a new keyword
The new operator in C++ is used for dynamic memory allocation. The memory is allocated in a heap.
Code
#include <iostream>
using namespace std;
class ninja {
string name;
int id;
string language;
public:
void get_NinjaData() {
cout << "Name : " << name << endl;
cout << "ID: " << id << endl;
cout << "Preferred Language: " << language << endl;
}
void set_NinjaData(string n, int i, string l) {
name = n;
id = i;
language = l;
}
};
int main() {
ninja * pointer = new ninja;
(*pointer).set_NinjaData("Ninja1", 101, "Java");
(*pointer).get_NinjaData();
return 0;
}
You can also try this code with Online C++ Compiler
Using “pointer” instead of (*pointer) above will result in an error as the variable pointer is the address. To use it, we will have to dereference it. So we dereferenced it using * and made a function call, i.e., get_data()
Output
Accessing Member Functions using Arrow operator
We have seen in the above example how we can access member functions and data members of objects using the dot operator and pointers. There is also another way of accessing these, and that is by using the Arrow operator. This operator uses pointers to access public data members and functions. The arrow operator is the combination of (-)minus operator and (>) greater than operator.
Code
#include <iostream>
using namespace std;
class ninja {
public: string name;
int id;
string language;
public: void get_NinjaData() {
cout << "Name : " << name << endl;
cout << "ID: " << id << endl;
cout << "Preferred Language: " << language << endl;
}
void set_NinjaData(string n, int i, string l) {
name = n;
id = i;
language = l;
}
};
int main() {
ninja obj;
ninja * pointer = & obj;
pointer -> name = "Ninja1";
pointer -> id = 101;
pointer -> language = "Java";
obj.get_NinjaData();
return 0;
}
You can also try this code with Online C++ Compiler
Similarly, other member functions and data members of a class can be accessed using the arrow operator and pointers.
Accessing Array of Objects using Pointers
We can initialize a pointer “ptr” storing an object of data-type “student” according to the integer “size”.this creates an array of objects, i.e., student.
Syntax
int size=3;
student *ptr=new student[size];
You can also try this code with Online C++ Compiler
The memory is allocated to an array of objects. In the above code, we ask the compiler for a memory of size equal to store three objects of a class Ninja. The address of the first block is stored in pointer ptr. We can access other blocks of memory by incrementing the pointer. For example, we want to create Ninja1, Ninja2, and Ninja3 as our objects. Then we can set a pointer that points to the memory of the first object in the array of objects. We can run a for loop till the size of the array of objects, i.e. (in our case, is 3). At each iteration, we are asking for data, using “cin” and calling the function “set_data( )” to set the values of the data members. After accessing the data members of an object, we are incrementing our pointer that points to the next object.
Code:
#include <iostream>
using namespace std;
class Ninja {
string Ninja_name;
int Ninja_id;
public:
void get_NinjaData() {
cout << "Ninja name is :" << Ninja_name << endl;
cout << "Ninja number is:" << Ninja_id << endl;
}
void set_NinjaData(string x, int y) {
Ninja_name = x;
Ninja_id = y;
}
};
int main() {
int size = 3;
Ninja * ptr = new Ninja[size];
Ninja * ptr2 = ptr;
string n;
int n_id;
cout << "enter three Ninja's name and their id :" << endl;
for (int i = 0; i < size; i++) {
cin >> n >> n_id;
ptr -> set_NinjaData(n, n_id); // or (*ptr).set_NinjaData(n,n_id);
ptr++;
}
// using set_data
for (int j = 0; j < size; j++) {
cout << " Ninja Id :" << j + 1 << endl;
ptr2 -> get_NinjaData(); // or (*ptr).set_NinjaData(n,n_id);
ptr2++;
}
return 0;
}
You can also try this code with Online C++ Compiler
The “this” keyword is an implicit pointer, used inside a member function for invoking an object. Only member functions have this pointer. Each object contains its own copy of the data member. This means that each object gets its own data member’s copy, and a single copy of member functions is shared by all the objects. Now here, one might get confused as, when only a single copy of each member function is made, how can we access and update the data members? To achieve the same, we use this pointer. Therefore this pointer is passed as a hidden argument for all non-static member function calls. But it is not available in the static member function. The this pointer is beneficial when the name of the local variable is same as the name of the instance variable. This scenario is also known as shadowing.
The code below represents the above case:
Code:
#include <iostream>
using namespace std;
class Ninja {
string Ninja_name;
int Ninja_no;
public:
// for accessing data members
void get_NinjaData() {
cout << "Ninja number is: " << this -> Ninja_name << endl;
cout << "Ninja number is: " << this -> Ninja_no << endl;
}
// here the name of the local variable is same as the name of the instance variable
void set_NinjaData(string Ninja_name, int Ninja_no) {
this -> Ninja_name = Ninja_name;
this -> Ninja_no = Ninja_no;
}
};
int main() {
Ninja * pointer = new Ninja;
(*pointer).set_NinjaData("CodingNinja", 2);
(*pointer).get_NinjaData();
return 0;
}
You can also try this code with Online C++ Compiler
When we assign a NULL value to the pointer, it is called a Null pointer. Whereas, a void pointer have no data type associated with it. It can store address of any data type. To print its value it must be typecasted.
What operators are used to access an object’s data members using a pointer?
We use the dereferencing operator(*) and (&)Indirection operator in order to access an object’s data members using a pointer.
How is memory allocated when we use the “new” keyword?
Memory is allocated dynamically whenever we use the “new” keyword.
What is the use of this keyword?
The this keyword is an implicit pointer. It is used to access data members and member functions. The currently executing object can also be accessed using this keyword. It is also used to resolve shadowing.
Conclusion
We hope this article helped you understand the concept of pointer to object in C++. We have also discussed how we can access data members and member functions of an object using a pointer, the usage of the arrow operator and pointer, and the array of objects and pointers. You can refer to our other articles for a better understanding of object-oriented programming:
You will find straightforward explanations of almost every topic on this platform you can read more such articles on our platform, Coding Ninjas Studio. . So take your learning to the next level using Coding Ninjas.