In C++, there are two ways to create objects, that is to say, to instantiate a class:
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:
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:
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
Published by jak58
Latest update on January 31, 2013 at 11:21 AM by jak58.