0

If I have a class named Object, what's the difference between creating an instance just like that:

#include <stdio.h>

Object var;

main ()
{
    var.test();
}

or

#include <stdio.h>

main ()
{
    Object* var = new Object();
    var->test();
}

Which is the differente between a global object (which you can use wherever you want) and create a dynamic object in the main.cpp? In theory it should be the same, right? The both method can be used in any file.cpp.

6
  • 4
    you mix two different concepts: scope and allocation Commented Nov 19, 2018 at 9:40
  • There are many differences, one of them being that your second code example didn't run the destructor, and leaked the memory relying on the OS to recover it for you. (Which is why you should never use "owning" naked pointers in C++.) What is your actual question (and what's with the <stdio.h>? That's a C header that should not appear in C++.) Commented Nov 19, 2018 at 9:40
  • This question seems a bit too broad for Stack Overflow, but any good C++ book should cover the problem of C++ memory model. Commented Nov 19, 2018 at 9:40
  • 3
    There is one common scheme for both approaches (global variable and raw operator new): you shouldn't use them if you don't have to :) Commented Nov 19, 2018 at 9:41
  • In the second case, add the function void func() {var->test();} before main() and you'll find it won't compile. You're mixing the concepts of scope and object lifetime - they are very different things, even if they sometimes go together. Commented Nov 19, 2018 at 10:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.