Anup Buchke
Anup Buchke

Reputation: 5500

Operator overloading assignment operator

#include<iostream>

using namespace std;


class shared_ptr
{
    public:
    int *pointer;
    public:
    shared_ptr()
    {
        pointer = new int;
    }
    ~shared_ptr()
    {
        delete pointer;
    }
    int operator* ();
    int* operator= (shared_ptr&);
};

int shared_ptr:: operator* ()
{
    return *(this->pointer);
}

int* shared_ptr:: operator= (shared_ptr& temp)
{
    return (temp.pointer);
}

int main()
{
    shared_ptr s1;
    *(s1.pointer) = 10;
    cout << *s1 << endl;
    int *k;
    k = s1;         //error
    cout << *k << endl;
}

I am trying to create something like smart pointer.

I am getting the following error while trying to overload operator = .

prog.cpp:39:9: error: cannot convert ‘shared_ptr’ to ‘int*’ in assignment for the k = s1 assignment line. What am I missing here?

Upvotes: 1

Views: 176

Answers (2)

Kostia
Kostia

Reputation: 271

Your Operator = returns int* but you don't have a constructor that gets int*, add:

shared_ptr(int *other)
{
    pointer = new int(*other);
}

Upvotes: 1

RiaD
RiaD

Reputation: 47620

You did provide operator = for

shared_ptr = shared_ptr 

case(very strange operator btw). But you are trying to use

int* = shared_ptr

You need either getter or cast-operator in shared_ptr to make it possible

Actually you may use it like

shared_ptr s1, s2;
...
int* k = (s1 = s2);

Demo

But it's absolutely ugly

Upvotes: 1

Related Questions