mardi 21 juillet 2020

Referencing in Operator Overloading

I'm new to the concept of operator overloading and I've just implemented a program to overload the assignment operator using a class. Here's the code I've implemented:

#include<iostream>

using namespace std;

class Test{
    private:
        int id;
        string name;
    public:
        Test():id(0),name(""){

        }
        Test(int id,string name):id(id),name(name){

        }
        
        
    
        void print(){
            cout<<id<<" : "<<name<<endl<<endl;
        }
        const Test &operator=(const Test &other){
            cout<<"Assignment Running"<<endl;
            id=other.id;
            name=other.name;
            return *this;
        }
        Test(const Test &other){
        cout<<"Copy Constructor Running"<<endl;
        id=other.id;
        name=other.name;
        }

};

int main(){
    Test test1(10,"Raj");
    cout<<"Test1 running\n";
    test1.print();


    Test test2;
    test2=test1;
    
   
    cout<<"Test2 running\n";
    test2.print();


    Test test3;
    test3.operator=(test2);                 //It's working as test2=test1
    
    cout<<"Test3 running\n";
    test3.print();

    Test test4=test1;
    cout<<"Test4 Running"<<endl;
    test4.print();

    return 0;
}

OUTPUT:

Test1 running
10 : Raj

Assignment Running
Test2 running
10 : Raj

Assignment Running
Test3 running
10 : Raj

Copy Constructor Running
Test4 Running
10 : Raj

In this function:

 const Test &operator=(const Test &other){
            cout<<"Assignment Running"<<endl;
            id=other.id;
            name=other.name;
            return *this;
        }

If I write operator= instead of &operator=, the OUTPUT changes to:

Test1 running
10 : Raj

Assignment Running
Copy Constructor Running
Test2 running
10 : Raj

Assignment Running
Copy Constructor Running
Test3 running
10 : Raj

Copy Constructor Running
Test4 Running
10 : Raj

Can someone explain what is happening in both cases ?? Nd yeah one more thing to note is that in the member function const Test &operator=, what's the use of const,I've tried to remove it and the OUTPUT is unaffected??

Aucun commentaire:

Enregistrer un commentaire