See the following code:
#include<iostream>
#include<stdlib.h>
using namespace std;
class ex
{
int i;
public:
ex(int x){
i=x;
cout<<"\nconstructor";
}
void setval(int x)
{
i=x;
}
int geti(){return i;}
~ex()
{
cout<<"\ndestructor";
}
};
int main()
{
ex *ob;
ob=(ex*) malloc(sizeof(ex));
ob->setval(5);
cout<<ob->geti();
delete ob;
}
I thought the above code would show an error but it compiles successfully and shows the output
5
destructor
Process returned 0 (0x0) execution time : 0.270 s
My question is:
Can I allocate memory for objects using
malloc
?How does
malloc
allocate memory for the class without a constructor parameter?Can I use
malloc()
for allocation anddelete
for deallocate ornew
for allocation andfree()
for deallocation?How is the destructor called without a constructor?