Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating C++ objects

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?

like image 757
neuromancer Avatar asked May 02 '10 00:05

neuromancer


People also ask

Can you create objects in C?

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.

Why do we create object in C?

To use the data and access functions defined in the class, you need to create objects.

What is object in C with example?

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.

Can we do OOP in C?

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.


1 Answers

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).

like image 128
ckarras Avatar answered Oct 17 '22 06:10

ckarras