samedi 17 septembre 2022

Issue in operator overloading using smart pointers

I am learning smart pointers in C++11. I am facing an compilation error with operator overloading using smart pointers. Can someone please suggest where I am doing wrong.

Below is the code

#include <iostream>
#include <memory>

using namespace std;

class myClass
{
   private:
   string name;

   public:
   myClass() { }
   myClass(string n) : name(n)  { }

   shared_ptr<myClass> operator + (shared_ptr<myClass> &obj1, shared_ptr<myClass> &obj2)
   {
      cout << "Operator Overloading" << endl; 
      return make_shared<myClass>(obj1 + obj2);
   }

   void print()
   {
      cout << name << endl;
   }
};

int main()
{
   shared_ptr<myClass> myPtr1 = make_shared<myClass>("Hello");
   myPtr1->print();

   shared_ptr<myClass> myPtr2 = make_shared<myClass>("Operator Overloading");
   myPtr2->print();

   shared_ptr<myClass> myPtr3;
   myPtr3 = myPtr1 + myPtr2; //Calling Operator overloading
   myPtr3->print();

   return 0;
}

Aucun commentaire:

Enregistrer un commentaire