Reference to Dynamic Objects in C++
Last Updated :
07 Mar, 2022
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++
#include<iostream>
using namespace std;
class Test
{
int a, b;
public :
Test()
{
cout << "Constructor is called" <<
endl;
a = 1;
b = 2;
};
~Test()
{
cout << "Destructor is called" <<
endl;
}
void show()
{
cout << "a = " <<
a << endl;
cout << "b = " <<
b << endl;
}
};
int main()
{
Test *ptr;
ptr = new Test;
ptr->show();
delete ptr;
return 0;
}
|
Output
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++
#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;
}
};
int main()
{
student &s1 = *( new student);
s1.setdata(1, "Ajay" );
s1.outdata();
student &s2 = *( new student);
s2.setdata(2, "Aman" );
s2.outdata();
student &s3 = *( new student);
s3.setdata(3, "Akshay" );
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...