I tried out this sample program

int main()
{

int *i=new int;
return 0;
}

The return type of new is a void pointer . Pasted below void* operator new(std::size_t); int *i=new int; new int in the above statement should return void pointer .

How can a void pointer be stored in int pointer ?
Sounds silly but i guess someone will bring in more light on this .

Recommended Answers

All 3 Replies

do you mean NULL pointer?
if so a simple
int *i=NULL;
return i;
would work if the function is
int * operator_new(std::size_t);

From cplusplus.com

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

Lines 10 - 12 are the relevant lines and explain what's going on. There's a typecast to int*.

commented: Good One. Thanks +0

There is the non-associated global operator ::new that returns a void* type, but there is (implicit) typed operator new for all data types. So, in your case, calling "new int" will indeed return an integer value, and "new int[10]", will return an array of 10 integers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.