Reference to Dynamic Objects in C++
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically. The dynamic objects can be created with the help of pointers.
Syntax:
ClassName *ptr_obj; // pointer to object
ptr_obj = new ClassName // Dynamic object creation
delete ptr_obj; // Delete object dynamically
Below is the C++ program to implement the dynamic objects.
C++
// C++ program to implement // dynamic objects #include<iostream> using namespace std; // Class definition class Test { // Data members int a, b; public : // Constructor to initialize // data members of class Test() { cout << "Constructor is called" << endl; a = 1; b = 2; }; // Destructor ~Test() { cout << "Destructor is called" << endl; } // Function to print values // of data members void show() { cout << "a = " << a << endl; cout << "b = " << b << endl; } }; // Driver code int main() { // pointer to object Test *ptr; // dynamic object creation ptr = new Test; // Accessing member through // pointer to object ptr->show(); // Destroying object dynamically delete ptr; return 0; } |
Constructor is called a = 1 b = 2 Destructor is called
Reference to Dynamic Objects
The address of dynamic objects returned by the new operator can be dereferenced and a reference to them can be created.
Syntax:
ClassName &RefObj = * (new ClassName);
The reference to object RefObj can be used as a normal object. The memory allocated to such objects cannot be released except during the termination of the program.
Below is the program of Reference to Dynamic Objects in C++.
C++
// C++ program to implement // Reference to dynamic objects #include<iostream> #include<string.h> using namespace std; class student{ private : int roll_no; char name[20]; public : void setdata( int roll_no_in, char name_in[20]) { roll_no = roll_no_in; strcpy (name, name_in); } void outdata() { cout << "Roll No is: " << roll_no << endl; cout << "Name: " << name << endl; } }; // Driver code int main() { // Reference to dynamic object student &s1 = *( new student); s1.setdata(1, "Ajay" ); s1.outdata(); // Reference to dynamic object student &s2 = *( new student); s2.setdata(2, "Aman" ); s2.outdata(); student &s3 = *( new student); s3.setdata(3, "Akshay" ); // Reference to static object student &s4 = s3; s3.outdata(); s4.outdata(); return 0; } |
Output:
Roll No is: 1
Name: Ajay
Roll No is: 2
Name: Aman
Roll No is: 3
Name: Akshay
Roll No is: 3
Name: Akshay