C++ : The objects

Ask a question

Creating objects

In C++, there are two ways to create objects, that is to say, to instantiate a class:
  • Statically
  • Dynamically

Creating static object

The creation of static objects implies creating an object by assigning a name to it, as you would do for a variable:
Name_of_class Name_of_objet;

Thus, the object is accessed through its name ...

Creating a dynamic object

The creation of a dynamic object implies the creation of an object by the program itself according to its "needs". The dynamic objects don't have a name to easily, instead they can be identified by pointers.
During the creating a dynamic object:
  • Definition of a pointer to a given class.
  • Create the object using the new keyword, which will also return the address of the newly created object.
  • Assign the address to the pointer.

The syntax is as follows:
Class_name* Pointer_name; 
Pointer_name = new Class_Name;

Using this pointer, you will be able to manipulate the "dynamic" object (functions and/or data members).
Any object created dynamically using the new keyword should be destroyed at the end of its use using the delete keyword. Otherwise, it will unnecessarily occupy a portion of the memory (even after closing the program). Objects created statically do not need to be destroyed, they are automatically deleted. Following the removal of a dynamic object, the memory it occupied is freed. You must then assign the NULL value to the pointer.

Access the data members of an object

Access to the data members of an object is done differently depending on whether the object was created statically or dynamically:
  • For objects created statically, the access to data members is done through the name of the object followed by a dot (.), Then the name of the data member. For example:

Object_name.Data_Member_Name = Value;
  • As for dynamic objects, access to data members is done through the pointer:

Pointer_name-> Data_Member_name = Value;
  • If ever the data member is the pointer of an object, you can access its data members through the current object:

Pointer_name->Data_Member_name->Data_Member_name = Value;

Access to the member functions

Access to the functions of an object is done in the same way as for data members:
For static objects:

For dynamic objects :

Original document published on CommentcaMarche.net.
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team