Creating and Accessing Dynamic Objects in C++

To create an object dynamically, invoke the constructor for the object using the syntax new ClassName(arguments).

You can also create objects dynamically on the heap using the syntax shown below.

ClassName* pObject = new C1assName(); or

ClassName* pObject = new ClassName;

creates an object using the no-arg constructor and assigns the object address to the pointer.

ClassName* pObject = new ClassName(arguments);

creates an object using the constructor with arguments and assigns the object address to the pointer.

For example,

// Create an object using the no-arg constructor
string* p = new string(); // or string* p = new string;

// Create an object using the constructor with arguments
string* p = new string(“abcdefg”);

To access object members via a pointer, you must dereference the pointer and use the dot (.) operator to object’s members. For example,

string* p = new string(“abcdefg”);

cout << “The first three characters in the string are “

<< (*p).substr(0, 3) << endl;

cout << “The length of the string is ” << (*p).length() << endl;

C++ also provides a shorthand member selection operator for accessing object members from a pointer: arrow operator (->), which is a dash (-) immediately followed by the greater- than (>) symbol. For example,

cout << “The first three characters in the string are “

<< p->substr(0, 3) << endl;

cout << “The length of the string is ” << p->length() << endl;

The objects are destroyed when the program is terminated. To explicitly destroy an object, invoke

delete p;

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *