What are the differences

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Idiot {
    public:
        Idiot();
        ~Idiot();
    private:
        unsigned short int level;
};

Idiot::Idiot() {
    level = 99;
}

int main()
{
    Idiot jason;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using namespace std;

class Idiot {
    public:
        Idiot();
        ~Idiot();
    private:
        unsigned short int *level;
};

Idiot::Idiot() {
    level = new unsigned short int(99);
}

int main()
{
    Idiot jason;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Idiot {
    public:
        Idiot();
        ~Idiot();
    private:
        unsigned short int level;
};

Idiot::Idiot() {
    level = 99;
}

int main()
{
    Idiot *jason = new jason;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Idiot {
    public:
        Idiot();
        ~Idiot();
    private:
        unsigned short int *level;
};

Idiot::Idiot() {
    level = new unsigned short int(99);
}

int main()
{
    Idiot *jason = new jason;
}



The book that I'm currently reading didn't explain it :(
The difference is in how memory is being allocated. The examples making use of the new keyword are dynamically allocating memory on the heap, and need to manually be freed by using delete (which you'd probably do in the destructor in this case).
Hi, could you please differentiate the four which confuses me? :)
You should research dynamic memory allocation and stack vs heap. Very interesting topics and by doing so, you'll be able to fully understand what's going on in these code snippets.

Dynamic memory: http://www.cplusplus.com/forum/articles/416/
Stack and Heap: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
Example 1:
Everything is on the stack, i.e. there is no additional memory being allocated at runtime.

Example 2:
The member variable is now a pointer, and the program reserves some space in memory via the operator new. This is like:
1
2
int I; //Except I exists only after new is called and only before delete is called
int *j = &I;

In this case, the memory can should be deallocated in the class's destructor, and the user will be none the wiser that there was memory allocation going on in the background.

Example 3:
This time the object itself is a pointer that points to some allocated space for an object the size of the class Idiot. The user will be responsible for freeing up that memory.

Example 4:
A combination of Examples 2 and 3.

I hope the author(s) wrote in deallocation examples as an extension to these. The three latter examples show a case of memory leaks because there is no deleteing of the pointers.
Topic archived. No new replies allowed.