Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
About Pointers in C++
3.
Syntax of a Pointer 
4.
Accessing Member Functions
4.1.
Accessing Member Functions without Pointers 
4.2.
Accessing Member Functions with Pointers 
4.3.
Accessing Member Functions using a new keyword 
4.4.
Accessing Member Functions using Arrow operator
4.5.
Accessing Array of Objects using Pointers
5.
This pointer
6.
Frequently Asked Questions
6.1.
How Null pointer is different from void pointer?
6.2.
What operators are used to access an object’s data members using a pointer?
6.3.
How is memory allocated when we use the “new” keyword?
6.4.
What is the use of this keyword?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What is Pointer to Object in C++

gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

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. 

Pointer to Object in C++

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 Pointers article to learn more about pointers and their types.

Fibonacci Series in C++

About Pointers in C++

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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;

Here data type of the pointer is the same as the variable's data type, where ‘*’ is the indirection operator, and ‘&’ is the address operator.

We know that objects in C++ are created from a user-defined data type called class. Classes have data members and member functions.

  1. Data members: When we define a class, we initialize some data variables. These are known as data members.
     
  2. Member Functions: We can use these functions to manipulate the data members in user-defined classes.

Accessing Member Functions

Accessing Member Functions without Pointers 

In the below example, we will see how we access member functions in classes without using Pointers.

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 obj;
  cout << "Member functions are Accessed without pointers." << endl;
  obj.set_NinjaData("Ninja1", 101, "Java");
  obj.get_NinjaData();
  return 0;
}  

Output

Output

In the above example, the object is created using static allocation.

Accessing Member Functions with Pointers 


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 obj;
  ninja * pointer = & obj;
  cout << "Member functions are Accessed using pointers." << endl;
  ( * pointer).set_NinjaData("Ninja1", 101, "Java");
  ( * pointer).get_NinjaData();

  return 0;

}

Output

Output

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;

}

 

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
 

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;
}

Output

Output


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];

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;
}

 

Output

This pointer

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;
}

Output:

Output

“this” pointer can access an object's data members and member functions.

Similarly, we can access member functions with the help of the “this” pointer.

You can also practice with the help of Online C++ Compiler

Frequently Asked Questions

How Null pointer is different from void pointer?

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. 

Happy Coding!

Previous article
Dangling, Void, Null and Wild Pointers
Next article
Introduction to Array
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass