-1

need detailed explanation on the 'new' operator in C++. Can somebody explain why the following works:

int *n = new int(10);  // initialize the pointer to integer as '10'
cout << *n;            // o/p -> 10

but this does not work?

int p = new int (10);  // error: invalid conversion from 'int*' to 'int' [-fpermissive]
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
b.s.
  • 1
  • 2

2 Answers2

0

new operator used with pointers, not int type so

   int x = 5;
   int *p = &x;
   int *q = new int(4);

and you can use it with classes struct, so on but not pure types I mean just int char .. etc.

this is the declaration of new :

  void* operator new[] (std::size_t size);
  void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
  void* operator new[] (std::size_t size, void* ptr) noexcept;

as what you see it's return pointer type void so you cann't in c/c++ write

  int x = p; // error : invalid conversion from 'int*' to 'int'

which is the same as what you did.

0

It is quite evident from the error message itself.. error: invalid conversion from 'int*' to 'int'

Since "new" returns a pointer if it is successful. That's why you are getting an error when you are trying to assign it to an int.

Sid
  • 43
  • 7