1

Coming from Java, I have a tendency to use the new keyword all the time in C++, but isn't this dangerous? I know about heap allocation and whatnot, but when in C++, is new actually necessary?

I guess my question is how do I initialize an object without the new keyword?

class Foo {
    int bar;
}

Given this class, this is instantiating it with the new keyword:

Foo aFoo = new Foo;

Is this the correct way to instantiate the Foo object without new?

Foo aFoo = Foo;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mitchell Carroll
  • 449
  • 5
  • 13
  • When the size of something is not known at compile time. Also, use smart pointers (C++11) – AndyG Oct 01 '14 at 16:47
  • 4
    Forget everything you know about Java. Everything. Treat C++ as something _totally_ different and unrelated because, y'know, it _is_. – Lightness Races in Orbit Oct 01 '14 at 17:21
  • But it isn't. Java syntax was based on C++ syntax and Java was meant to be like C++ but address some of the most annoying things about C++, like pointers and portability. My question is now purely syntactical and only has to do with C++. – Mitchell Carroll Oct 01 '14 at 17:27
  • 2
    Neither of your examples of instantiating a `Foo` object is valid C++. The first would be valid Java. You really need [a good C++ book](http://stackoverflow.com/q/388242/10077). – Fred Larson Oct 01 '14 at 18:05
  • @MitchellCarroll: I am telling you, it is. – Lightness Races in Orbit Oct 02 '14 at 14:21
  • @MitchellCarroll A language is more than syntax, it is also about semantics, conventions, and mindset. Though Java borrowed much syntax from C++, but works does not behave like C++: C++ uses value semantics if you do not specify anything else. C++ uses the RAII machinery to manage resources. C++ does not say that everything is an Object, though you can use void* if you really have to. From a software design perspective, C++ apps should avoid inheritance, and favor free functions, and possible also take advantage of ADL. Thus, you should learn C++ as a new language. – user877329 Aug 11 '19 at 06:58

1 Answers1

0

If you create an object with new, you will be able to access this object from every code of your application, but if you do not delete it, it will be using memory. You can also create objects without new (not using pointers) but those will be deleted when out of scope.

fredcrs
  • 3,338
  • 6
  • 29
  • 52