×

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type.

Void Pointer Syntax:

void *ptr;  

We can't assign a variable's address to a variable of a different data type in C++.To better understand this let see an example below:

int *ptr;  //declaration of an integer pointer ptr 
float i=14.6; // initialization of a floating variable i
ptr= &i;  // This statement throws an error.

Explanation:

We define a pointer of type integer, ptr, and a float variable, 'i', in the preceding example. We try to save the address of 'i' variable in 'ptr' after declaration, but this is not feasible in C++ since the variable cannot carry the addresses of various data types.

Another example of a program containing void pointer in C++:

#include <iostream> 
#inlcude <bits/stdc++.h> 
using namespace std; 
int main()  
{  
    int *ptr;  
    float i= 14.6;  
    ptr = &i; // error  
    std::cout << "The value of *ptr is : " <<*ptr<< std::endl;  
    return 0;  
}

OUTPUT:

error: cannot convert ‘float*’ to ‘int*’ in assignment
ptr = &f; //error

Explanation:

In the above program, we define an integer pointer and a float variable. An integer pointer variable cannot point to a float variable, but it can only point to an integer variable. The above problem was solved in C++ by utilizing the void pointer, which may contain the address of any data type.

Another example of a program containing void pointer in C++:

#include <iostream>  
#include <bits/stdc++.h>
using namespace std;  
int main()  
{  
  void *ptr;   // declaration of a void pointer 
  int i=19;   //  initialization of an integer variable
  ptr=&i;   // storing the address of 'i' variable in a void pointer variable ptr.  
  std::cout << &i << std::endl;  
  std::cout << ptr << std::endl;  
  return 0;  
}

OUTPUT:

0x61ff08
0x61ff08
press any key to continue……

Explanation:

We declare void pointer variable and integer variable in the preceding program, which contains the address of void pointer integer variable.

Advantages of Void Pointer in C++

  • Because malloc() and calloc() return the void * type, they may be used to allocate memory of any data type (due to the void *).
  • Normal functions in C are executed using void pointers. For example, in qsort, the compare function is used ().

Important fact: It is not possible to ignore void pointers. The following program, for example, does not compile.

#include<stdio.h>
#include<iostream>
#include<bits/stdc++.h>
int main()
{	int i = 10;
	void *ptr = &i;
	printf("%d", *ptr);
	return 0;
}

OUTPUT:

Compiler error: 'void*' is not a pointer-to-object type

Following program run fine with the compiler:

#include<stdio.h>
#include<iostream>
#include<bits/stdc++.h>
int main()
{int i = 20;
void *ptr = &i;
printf("%d", *(int *)ptr);
return 0;
}

OUTPUT:

20

Related Topics

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.