The Wayback Machine - https://web.archive.org/web/20240918143440/https://www.geeksforgeeks.org/reference-to-dynamic-objects-in-cpp/
Open In App

Reference to Dynamic Objects in C++

Last Updated : 07 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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;
}


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++




// 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



Similar Reads

How to Restrict Dynamic Allocation of Objects in C++?
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java &amp; C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scop
2 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors:
6 min read
Introduction to Complex Objects and Composition
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation
4 min read
Anonymous Objects in C++
Prerequisite: Class and Objects in C++ An Object is an instance of a Class. A class has no memory allocated it is just like a blueprint, but when it is instantiated (i.e. an object is created) memory is allocated just like the real-world instance of that blueprint. An object that does not have a reference variable is known as an anonymous object. T
4 min read
Creating a Vector of Class Objects in C++
Prerequisites: Object Oriented Programming in C++Vector in C++ Class is a user-defined data type that can be accessed by creating objects or instances of that class. A vector is a type of container which can store elements of a similar type. Vector of Class The vector of class objects is an example of a custom vector made where we can store multipl
3 min read
How to Parse an Array of Objects in C++ Using RapidJson?
RapidJSON is an open-source C++ library for parsing and serializing JSON (JavaScript Object Notation) data. It is designed to be fast and efficient, with a focus on simplicity and ease of use. It is widely used in a variety of applications and is known for its fast performance and low memory overhead. It is a popular choice for parsing and serializ
4 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '&gt;&gt;' and &lt;&lt;' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
Array of Objects in C++ with Examples
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in
5 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 min read
Dynamic Constructor in C++ with Examples
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. Example 1: C/C++ Code #include &lt;iostream&gt; using namespace std; class geeks { const char* p; public: // default constructor geeks() { // allocating memo
3 min read
Dynamic Binding in C++
Dynamic binding in C++ is a practice of connecting the function calls with the function definitions by avoiding the issues with static binding, which occurred at build time. Because dynamic binding is flexible, it avoids the drawbacks of static binding, which connected the function call and definition at build time. In simple terms, Dynamic binding
3 min read
How to Create a Dynamic 2D Array Inside a Class in C++?
A dynamic array is an array that can grow, resize itself, contains a dynamic table, which is mutable in nature, or an array list is randomly accessible, the variable-size list data structure that allows elements to be added or removed. Suppose we want to create a class for Graph. The class stores the adjacency matrix representation of the graph. Ex
3 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
What is Dynamic Memory Allocation?
Resources are always a premium. We have strived to achieve better utilization of resources at all times; that is the premise of our progress. Related to this pursuit, is the concept of memory allocation.Memory has to be allocated to the variables that we create, so that actual variables can be brought to existence. Now there is a constraint as how
5 min read
How to Create a Dynamic Library in C++?
In C++, dynamic libraries also known as shared libraries are a powerful way to modularize your code. They allow the users to build libraries that can be loaded at runtime by multiple applications at once. This approach promotes code reuse, reduces code duplication, and simplifies maintenance of the codebase. In this article, we will learn how to cr
4 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
Can C++ reference member be declared without being initialized with declaration?
To many readers, this might sound the same thing, i.e. class_type *var = NULL; *var = &amp;some_work; is same as class_type *var = &amp;some_work; But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in another step, the compiler calls the default constr
2 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Reference to Array in C++
Reference to an array means aliasing an array while retaining its identity. Reference to an array will not be an int* but an int[]. Let us discuss this in detail by discussing the difference between these two. This is quite weird that int[] is the same as int* but still compiler perspective on both is entirely different. The major two differences a
4 min read
C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory location of the passed variable and parameter is the
5 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass
3 min read
Pass By Reference In C
Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program. Pass By Reference in C In this method, the address of an argument is passed to the function instead of the
4 min read
Pre-increment (or pre-decrement) With Reference to L-value in C++
Prerequisite: Pre-increment and post-increment in C/C++ In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement) can not be used as l-value. For example, following program prints a = 20 (++a is used as l-value) l-value is simply nothing but the memory location, which has an address. C/C++ Code // CPP p
2 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
Difference Between Call by Value and Call by Reference in C++
In C++ programming we have different ways to pass arguments to functions mainly by Call by Value and Call by Reference method. These two methods differ by the types of values passed through them as parameters. Before we look into the call-by-value and call-by-reference methods, we first need to know what are actual and formal parameters. The actual
4 min read
Practice Tags :