Difference between new and malloc.

  • new is an operator while malloc is function.
  • new calls constructor of a class while malloc does not.
#include<iostream>
using namespace std;

class foo{

public:
foo(){
cout<<"hello"<<endl;
}
~foo() { cout<<"bye"<<endl;}
};

int main()
{

foo *myfoo = new foo();
delete myfoo;
return 0;
}

Here we will get output from above program:

hello
bye
  • malloc returns void type while new returns exact data type.

 

  void *malloc(size_t size);
    foo *myfoo = new foo(); 



Related Contents to follow