I noticed that there are two ways to create C++ objects:
BTree *btree = new BTree;
and
BTree btree;
From what I can tell, the only difference is in how class objects are accessed (. vs. -> operator), and when the first way is used, private integers get initialized to 0.
Which way is better, and what's the difference?
How do you know when to use one or the other?
In terms of C programming, an object is implemented as a set of data members packed in a struct , and a set of related operations. With multiple instances, the data for an object are replicated for each occurrence of the object.
To use the data and access functions defined in the class, you need to create objects.
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality. Object is a runtime entity, it is created at runtime.
In principle OOP can be done in any language, even assembly. This is because all OO language compilers/assemblers (e.g. C++) ultimately translate the high level constructs of the language into machine language.
Two differences:
they create the objects in different parts of the memory (heap vs stack)
the object lifetime is different: In the first case, the code manages the memory allocation explicitly, and it must also manage the deallocation explicitly (using delete/delete[]).
In the second case, the object is automatically deallocated at the end of its enclosing scope (either a method, a nested block within a method, or a class)
Which one you uses depends mostly on the lifetime of the object (if it should outlive the method in which it is created or not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With