-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalnew.cpp
More file actions
42 lines (38 loc) · 905 Bytes
/
Copy pathmalnew.cpp
File metadata and controls
42 lines (38 loc) · 905 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdlib.h>
#include <iostream>
class MyClass
{
private:
int *_number;
public:
MyClass()
{
std::cout << "Allocate memory\n";
_number = (int *)malloc(sizeof(int));
}
~MyClass()
{
std::cout << "Delete memory\n";
free(_number);
}
void setNumber(int number)
{
*_number = number;
std::cout << "Number: " << _number << "\n";
}
};
int main()
{
/*
// allocate memory using malloc
// comment these lines out to run the example below
MyClass *myClass = (MyClass *)malloc(sizeof(MyClass));
myClass->setNumber(42); // EXC_BAD_ACCESS-> error coz constructor is not called and hence memory is not alocated for _number
free(myClass);
*/
// allocate memory using new
MyClass *myClass = new MyClass();
myClass->setNumber(42); // works as expected
delete myClass;
return 0;
}