0

I'm comming from "java-world" and now I want to start learning C++. I know in C++ objects are created like variables without the key word "new" which is used in java, but I have often seen in OOP code, when objects are create used by pointers like:

Car* car1 = new Car();
car1->doSomething();

instead of

Car car1;
car1.doSomething();

What's atually the difference? What's the advantage or disadvantage?

  • 3
    Your nightmare has just started. It's much easier to learn C++ if you know nothing about programming, than if you already know Java. Objects in C++ work completely differently than they do in Java -- and they are several degrees of magnitude more complex -- despite the deceivingly similar syntax, and unless you manage to forget everything you know about objects in Java, you will be perpetually confused. This is a very broad subject. Go buy a good book on C++, and start reading. This is the only way to learn this stuff. There are no shorcuts that someone on the intertubes can point you to. – Sam Varshavchik Aug 14 '16 at 21:34
  • `new` allocates a persistent object on the heap. The second method allocates a short-lived one on the stack. This difference is *extremely* important in C, C++ and related languages. Java hides all of this from you, so welcome to the real world. It's often a messy, ugly place, so be careful. You'll want to get a solid reference for C++ before digging any deeper, and the [one by the creator of the language](http://www.stroustrup.com/4th.html) is a good place to start. – tadman Aug 14 '16 at 21:35
  • You can declare class objects in three ways: `MyClass myClass;` which is a local stack variable and to access its members you use the `.` operator. The other two are both pointer types: the first being `MyClass* pMyClass;` this is a pointer to a class object, but this pointer has local stack storage same storage as your first `myClass` object. To access its members you use the `->` operator. The third as in the one you are talking about such as: `MyClass* pMyClass = new MyClass();` uses any of its constructors to create this pointer on the heap. You access its members with the `->` operator. – Francis Cugler Aug 14 '16 at 22:57
  • (...continued) The first two are in local scope of the function or block of code that it is declared or instantiated in. Once that block of code goes out of scope, the memory is destroyed. The last one which is heap memory is allocated in memory and it's scope or life time extends past the block that it was created in. Its memory does not automatically get cleaned up; either you the programmer or the user is responsible for managing this heap memory. So each time `new` or `new []` is used; there must be a matching `delete` or `delete []`. The only problem here is knowing when and where to. – Francis Cugler Aug 14 '16 at 23:02

0 Answers0