Assignment Operator Overloading in C++

In this C++ tutorial we are going to talk about the Assignment Operator. We will go over in detail, as to why they are used, where they are used and how they are used.

A little prior knowledge about the different types of Constructors and Classes will benefit you greatly in this tutorial. But don’t worry, we’ll cover as much as we can!


Introduction to Assignment Operator

The Assignment Operator is a special type of function, which is called when the assignment ( = ) operator between two pre-existing objects.

Below is a small example of how a Assignment Operator could be triggered.

Object obj1;
Object obj2;

obj1 = obj2;   // Assignment Operator Called

There is of course, a default Assignment Operator present without us declaring one. However, there may be times that we want to define specific behavior while assigning objects. Or we might be dealing with dynamic memory, such as arrays allocated on the heap. In such cases, defining an Assignment Operator becomes a necessity.

The Assignment Operator is often confused with the Copy Constructor. So we will also be briefly discussing that here. The below code shows when an Copy Constructor is called.

Object obj1;
Object obj2 = obj1;   // Copy Constructor Called

In short, the Copy Constructor is called between an existing object, and an object being created. Unlike the Assignment Operator, which occurs between two existing objects.


Using the Assignment Operator

The assignment operator is actually one of many operator functions. We refer to this as operator overloading, where we overload one of these operator functions to define behavior for special situations.

Below is a simple example on how to overload the assignment operator.

#include<iostream>
using namespace std;

class Student {
    string name;
    int age;

    public:
    Student(int x, string s) {
        age = x;
        name = s;
    }

    Student() {}

    Student& operator = (const Student &s)
    {
        cout << "Assignment Operator Called" << endl;
        name = s.name;
        age = s.age;
        return *this;
    }

    Display() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    Student s1(5, "Bob");

    Student s2;
    s2 = s1;

    s2.Display();
}
Assignment Operator Called
Name: Bob
Age: 5

Example# 2

The Assignment Operator we did in the previous example was purely for demonstrative purposes, and had no practical value. The real necessity comes in when we deal with Dynamic data as we will show in this example.

Dynamic memory needs to be allocated newly in the Object being assigned to, and then the values can be copied over. Normally this isn’t a problem, because data is allocated on the stack, unlike dynamic memory, which is allocated on the heap, and must be deleted and allocated manually.

You will also notice we created Destructors, without which the program would crash, as the memory would not be freed.

#include<iostream>
using namespace std;

class Student {
    string name;
    int age;
    int numOfCourses;
    string *courses;

    public:
    Student(int x, string s, int n) {
        age = x;
        name = s;
        numOfCourses = n;
        courses = new string[n] { "" };
    }

    Student() {
        courses = NULL;
    }

    Student& operator = (const Student &s)
    {
        cout << "Assignment Operator Called" << endl;
        name = s.name;  // Copy over regular values first
        age = s.age;
        numOfCourses = s.numOfCourses;

        delete[] courses; // Free up old memory first
        courses= new string[numOfCourses]; // Create memory with new size

        // Copy over the values for Courses
        for (int i = 0; i < numOfCourses; i++) {
            courses[i] = s.courses[i];
        }

        return *this;
    }

    ~Student() {
        delete[] courses; // Free memory once object goes out of scope
    }

    Display() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    Student s1(5, "Bob", 3);

    Student s2;
    s2 = s1;

    s2.Display();
}

We didn’t enter any course details, hence there isn’t any output to show. Feel free to play around with it yourself though.


This marks the end of the Assignment Operator in C++ Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments