×

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an object from a function, a copy of the object is usually created. However, in some cases, it is necessary to prevent object copying in C++. In this article, we will discuss why we may want to prevent object copying and how to do it in C++.

Why Prevent Object Copying?

There are several reasons why we may want to prevent object copying in C++. One of the most common reasons is to prevent unintended side-effects when copying objects. For example, consider an object that represents a unique resource, such as a file handle. When you copy this object, you are creating two references to the same resource. This can lead to unintended behavior when one of the objects is used to modify the resource, as the changes will affect both objects.

Another reason to prevent object copying is to improve performance. Copying large objects can be a time-consuming operation, especially if the objects contain many data members. Preventing object copying can help to reduce the amount of time spent copying objects and can help to improve overall performance.

How to Prevent Object Copying in C++:

There are several ways to prevent object copying in C++.

1. Private Copy Constructor and Assignment Operator:

One of the most common methods of preventing object copying is to declare the copy constructor and assignment operator as private members in the class definition. This makes them inaccessible to client code and prevents the creation of objects using these methods.

Here's an example of a class definition that prevents object copying using this method:

class NonCopyable
{
private:
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};

In the example above, the copy constructor and assignment operator are declared as private members and are deleted using the delete keyword. This ensures that objects of this class can only be created and assigned using the default constructor and default assignment operator.

Program:

#include <iostream>




class NonCopyable
{
private:
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};


int main()
{
    NonCopyable obj1;
    // NonCopyable obj2 = obj1; // error: copy constructor is deleted
    // NonCopyable obj3;
    // obj3 = obj1; // error: assignment operator is deleted


    std::cout << "Objects created successfully!" << std::endl;
    return 0;
}

Explanation:

  • The code defines a class NonCopyable that is designed to prevent the creation of objects using the copy constructor and assignment operator.
  • The class definition has two private member functions, the copy constructor and the assignment operator, which are declared using the delete keyword.
  • This keyword indicates that the copy constructor and the assignment operator are inaccessible to client code and will result in a compile-time error if used.
  • The class also has a default constructor and a virtual destructor, which are both declared using the default keyword.
  • In the main function, objects of the NonCopyable class are created using the default constructor. Attempts to copy the objects using the copy constructor or the assignment operator result in compile-time errors, as these functions have been deleted.
  • Finally, a message is displayed indicating that the objects have been created successfully.

Program Output:

Preventing Object Copy in C++

2. Make the copy constructor and the copy assignment operator private members of the class:

Another way to prevent object copying in C++ is to make the copy constructor and the copy assignment operator private members of the class and not provide a definition for them. This makes them inaccessible to client code, and if they are used, it results in a linker error.

For example:

class NonCopyable
{
private:
    NonCopyable(const NonCopyable&);
    NonCopyable& operator=(const NonCopyable&);


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};

In this example, the copy constructor and the copy assignment operator are declared as private member functions but not defined. This makes them inaccessible to client code and results in a linker error if they are used.

This method is similar to the previous method, but it allows objects of the class to be passed by value or returned by value from functions, since the copy constructor and copy assignment operator are implicitly defined by the compiler. However, it also means that it is not immediately clear to client code that the objects of the class are not meant to be copied.

Program:

#include <iostream>


class NonCopyable
{
private:
    NonCopyable(const NonCopyable&);
    NonCopyable& operator=(const NonCopyable&);


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};


int main()
{
    NonCopyable obj1;
    // NonCopyable obj2(obj1); // error: copy constructor is private
    // NonCopyable obj3;
    // obj3 = obj1; // error: assignment operator is private


    std::cout << "Objects created successfully!" << std::endl;
    return 0;
}

Explanation:

  • In this program, a class NonCopyable is defined that has a private copy constructor and copy assignment operator. This means that these member functions can only be used by other members and friend functions of the NonCopyable class and are inaccessible to client code.
  • In the main function, an object obj1 of the NonCopyable class is created.
  • Attempts to create another object obj2 by copying obj1 using the copy constructor and to assign obj1 to another object obj3 using the copy assignment operator are commented out, as they would result in compile-time errors, due to the private access specifier for the copy constructor and copy assignment operator.
  • The program outputs the message "Objects created successfully!", indicating that the objects were created without any issues.

Program Output:

Preventing Object Copy in C++

3. final Keyword:

Another method to prevent object copying is to declare the class as final. The final keyword in C++11 prevents the class from being inherited, which in turn prevents the creation of objects using the copy constructor or assignment operator.

Here's an example of a class definition that prevents object copying using the final keyword:

class NonCopyable final
{


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};

In the example above, the final keyword is used to declare the class as non-inheritable, preventing the creation of objects using the copy constructor or assignment operator.

Program:

#include <iostream>


class NonCopyable final
{


public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};


int main()
{
    NonCopyable obj1;
    // NonCopyable obj2 = obj1; // error: copy constructor is deleted
    // NonCopyable obj3;
    // obj3 = obj1; // error: assignment operator is deleted


    std::cout << "Objects created successfully!" << std::endl;
    return 0;
}

Explanation:

This program demonstrates another way of preventing object copying in C++, using the final keyword. The code defines a class NonCopyable that is designed to prevent the creation of objects using the copy constructor and assignment operator.

The class definition uses the final keyword to indicate that the class cannot be subclassed. This has the side effect of making the copy constructor and assignment operator inaccessible to client code, thus preventing object copying.

The class has a default constructor and a virtual destructor, both declared using the default keyword.

In the main function, objects of the NonCopyable class are created using the default constructor. Attempts to copy the objects using the copy constructor or the assignment operator result in compile-time errors, as these functions are inaccessible due to the use of the final keyword.

Finally, a message is displayed indicating that the objects have been created successfully.

Program Output:

Preventing Object Copy in C++

4. Inherit a Dummy class with a private copy constructor and a private copy assignment operator:

One way to prevent object copying in C++ is to inherit a dummy class that has a private copy constructor and a private copy assignment operator. This dummy class can be used as a base class for the class that needs to prevent object copying.

Here's an example of how this technique can be implemented:

Program:

#include <iostream>


// Define a dummy class with private copy constructor and copy assignment operator.
class Dummy
{
private:
    Dummy(const Dummy&);
    Dummy& operator=(const Dummy&);
};


// Define a class that needs to prevent object copying.
class NonCopyable : public Dummy
{
public:
    NonCopyable() = default;
    virtual ~NonCopyable() = default;
};


int main()
{
    NonCopyable obj1;
    // NonCopyable obj2(obj1); // error: copy constructor is private
    // NonCopyable obj3;
    // obj3 = obj1; // error: assignment operator is private


    std::cout << "Objects created successfully!" << std::endl;
    return 0;
}

Explanation:

  • This program demonstrates how to prevent object copying in C++ using inheritance.
  • The program defines a dummy class named Dummy which has a private copy constructor and a private copy assignment operator.
  • These private functions make it impossible to create a new instance of the Dummy class by copying an existing object.
  • Next, the program defines another class named NonCopyable which inherits from the Dummy class.
  • By inheriting from Dummy, NonCopyable also acquires the private copy constructor and copy assignment operator, making it impossible to copy instances of the NonCopyable class.
  • In the main function, an instance of NonCopyable named obj1 is created.
  •  If we try to create another instance of NonCopyable by copying obj1, the program will give an error because the copy constructor is private.
  • Similarly, if we try to assign obj1 to another instance of NonCopyable, the program will give an error because the copy assignment operator is private.
  • Despite these errors, the program still runs and outputs "Objects created successfully!" to the console.

Error:

Preventing Object Copy in C++

Related Topics

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.