Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Pointer to Object in C++?
3.
How to use pointers?
4.
Syntax of pointer 
4.1.
Implementation
4.2.
C++
4.3.
Output 
5.
Types of Pointers in C++
6.
Null pointer
6.1.
Implementation
6.2.
C++
6.3.
Output
7.
Void pointer
7.1.
Implementation
7.2.
C++
7.3.
Output
8.
Array name as a pointer
8.1.
Implementation
8.2.
C++
8.3.
Output
9.
Wild Pointer 
9.1.
Implementation
10.
Dangling Pointer
10.1.
Implementation
10.2.
C++
11.
Advantages of using Pointers in C++
12.
Disadvantages of using Pointers in C++
13.
Frequently asked questions
13.1.
How do you initialize a pointer to an object in C++?
13.2.
Why use pointer to object instead of object C++?
13.3.
What is a pointer to a derived class object in C++?
13.4.
What is pointer to object member function in C++?
13.5.
How do I create a pointer to an object in C++?
13.6.
How do you dereference pointers to class objects C++?
13.7.
How do you access a pointer to an object?
14.
Conclusion
Last Updated: Mar 28, 2024
Easy

What is a pointer to an object in C++?

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

Introduction

Pointer is a variable that stores the address of another variable. Pointer allows you to refer to the same memory space from multiple locations. That means you can update the memory in one location, and the change can be seen from another location in your program.

pointer to object in c++

In this article, we will learn and explore what is a pointer to an object in C++? and their fundamental concepts.

What is Pointer to Object in C++?

In C++, a pointer to an object is like a special kind of variable that holds the memory address of an object. It provides a way to indirectly reach and work with the object, permitting us to use and interact dynamically. Pointers to objects come in handy when dealing with memory allocated dynamically, allowing us to use memory flexibly and create objects dynamically as needed.

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

How to use pointers?

  • First, we have to define a pointer variable.
  • After defining a pointer variable, we can assign the address of a variable to a pointer by using a unary operator (&).
  • To access the given variable’s value, we can use the pointer variable with the help of the unary operator (*). A unary operator is used before the pointer variable to get the value of that address stored in the pointer variable.
     

Also see, Literals in C, Fibonacci Series in C++  and,  Unary operator overloading in c++.

Syntax of pointer 

data_type *variable_name;

Here type is defined as the datatype, and variable_name is the pointer’s name in which you want to store the address of a given variable.

Implementation

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
int data = 20;

// declaration pointer variable
int * ptr;

// assigning the address of given variable to the pointer 
ptr = & data;

// gives the address that stored in pointer
cout << "Address in ptr=" << ptr << endl;

// value of the given variable
cout << "Value of data=" << data << endl;

// value of the given variable
cout << "Value at *ptr=" << * ptr << endl;
return 0;
}

Output 

Address in ptr=0x7ffe96baeaec
Value of data=20
Value at *ptr=20

Types of Pointers in C++

There are five types of pointers in C++  -

  1. Null Pointer
  2. Void Pointer
  3. Array Name as a Pointer
  4. Wild Pointer
  5. Dangling Pointer

Null pointer

The null pointer is a pointer that does not point to any memory location. It represents an invalid memory location. When we assign a NULL value to a pointer, then that pointer refers to a null pointer.

Implementation

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main() {

// declaration pointer variable
int * ptr;

// assigning NULL Address to the pointer
ptr = NULL;

// gives the address that stored in pointer 
cout << "Address in ptr=" << ptr << endl;

return 0;
}

Output

Address in ptr=0

Void pointer

The pointer with no associated data type is known as a void pointer. A void pointer can hold addresses of any type and can be typecast to any type.

Implementation

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
int var = 10;

// declaration of void pointer variable
void * ptr;
ptr = &var;

// gives the address that stored in pointer
cout << "Address in ptr=" << ptr << endl;

// typecating the pointer
cout << "Value at ptr=" << * (int * ) ptr << endl;

return 0;
}

Output

Address in ptr=0x7ffeca383a9c
Value at ptr=10


In the above code, you can see that we have defined a void pointer. This pointer has no associated data type. So, it can point to any type of data. In the ‘cout’ function, you can see that we have first typecasted the pointer into an integer pointer then dereferenced it.

Array name as a pointer

The array's name contains the address of the first element of the array, so you can not change the address stored in the array name. The array's name acts as a constant pointer. You can assign the address of an array to a pointer without using an ampersand (&).

Implementation

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
int arr[4] = {12,15,20,50};

// declaration of void pointer variable
int * ptr;

// assign the address of arr[0] to ptr
ptr = arr;
for (int i = 0; i < 4; i++) {
cout << * ptr << endl;

// increment pointer ptr by 1
ptr++;
}
return 0;
}

Output

12
15
20
50


With the help of the above example, you can clearly understand how we can print the elements of the array with the help of the pointer.

Wild Pointer 

A wild pointer in C++ is a pointer variable that hasn't been initialized to a valid memory address. It points to an unknown or random location in memory, potentially leading to program crashes, unexpected behavior, or security vulnerabilities.

Implementation

#include <iostream>
using namespace std;
int main() {
 // Declare a pointer to an integer, but don't initialize it
 int* ptr;  
 // Dereferencing a wild pointer (causes undefined behavior)
 cout << *ptr << endl;  // This will likely cause a segmentation fault
 return 0;
}

 

Output:

Attempting to dereference a wild pointer in C++ will typically result in a segmentation fault, which terminates the program abnormally. The exact output may vary depending on your system and compiler.

Dangling Pointer

A dangling pointer is a pointer that refers to a memory location that has been deallocated using delete or delete[] for arrays. The memory is no longer accessible, and attempting to dereference the pointer leads to undefined behavior, similar to a wild pointer.

Implementation

  • C++

C++

#include <iostream>

using namespace std;

int main() {
int* ptr = new int(10); // Allocate memory for an integer

// Deallocate the memory pointed to by ptr
delete ptr;

// Dereferencing a dangling pointer after deallocation (undefined behavior)
cout << *ptr << endl; // This may cause a segmentation fault

return 0;
}

Output

The output of this code is also undefined behavior. Dereferencing the pointer ptr after the memory it pointed to has been deallocated might result in a segmentation fault or crash.

You practice by yourself with the help of online c++ compiler.

Advantages of using Pointers in C++

Some advantages of using Pointers are given below:

  • Pointers are the variables that are used to store the address of other variables in C/C++.
  • Pointer allows us to allocate and deallocate the memory dynamically.
  • Pointers help us in simplifying the complexity of the program.
  • With the help of pointers, we can improve the execution speed of a program.
  • With the help of pointers, we can modify and return more than one variable from a function. 

Disadvantages of using Pointers in C++

 There are some disadvantages of using Pointers. They are as follows:

  • Normal variables are faster than pointers.
  • A segmentation defect may arise from an uninitialized pointer.
  • Incorrectly updating pointer bugs can result in memory degradation.
  • Handling pointer bugs is difficult, so using pointers effectively and correctly is important.

Frequently asked questions

How do you initialize a pointer to an object in C++?

In C++, initialize a pointer to an object using, nullptr (C++11+) to indicate no memory allocation and & operator with an existing object's address.

Why use pointer to object instead of object C++?

Pointers to objects offer:

  • Dynamic memory allocation (using new).
  • Passing objects by reference (functions modify original object).
  • Polymorphism (treating derived class objects as base class).

What is a pointer to a derived class object in C++?

A pointer to a derived class object can hold the address of a derived class object (base class pointer can also point to it).

What is pointer to object member function in C++?

A pointer to an object member function points to a specific member function of an object (used with the ->* operator).

How do I create a pointer to an object in C++?

In C++, we can create a pointer to an object by declaring a variable with the object's type followed by an asterisk (*) and the object's name. The syntax can be the class name along with the object pointer name.

How do you dereference pointers to class objects C++?

When a pointer is dereferenced, it becomes an alias for the object it points to. If 'a' is a pointer of type ABC, then *a represents the object of type ABC that 'a' points to. You can perform all operations applicable to an object of type ABC on *a.

How do you access a pointer to an object?

We can access data members and member functions operating the pointer name with an arrow -> symbol. For instance, if you keep a pointer called "x" to an object with a member function "happyCoding()," then you can access it using "x->happyCoding." Likewise, you can access the object's member variables by operating the arrow operator, such as "x->MemberVaribles."

Conclusion

That's all about pointers. This blog is over; we have learn What is a pointer to an object in C++? But the thirst for learning is not over yet. If you wish to prepare for technical interviews, you can visit our library of curated articles and blogs by clicking here.

Learn more: Data Structure

Till then, have a nice day and Happy Coding! 

Next article
Array of pointers
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass