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.

Path
  • 9
  • 2
  • 4
    you mix two different concepts: scope and allocation – bolov Nov 19 '18 at 09: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 ``? That's a C header that should not appear in C++.) – DevSolar Nov 19 '18 at 09:40
  • This question seems a bit too broad for Stack Overflow, but [any good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should cover the problem of C++ memory model. – Yksisarvinen Nov 19 '18 at 09: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 :) – lubgr Nov 19 '18 at 09: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. – Peter Nov 19 '18 at 10:24
  • first case object is created before calling main() while second case is after. – AIMIN PAN Nov 20 '18 at 03:31

0 Answers0