1
#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?

3
  • 1
    "What am I missing here?" A cast? Commented Jul 4, 2013 at 21:20
  • Can I have implementation where I dont need cast? I mean using this like pointers Commented Jul 4, 2013 at 21:22
  • to allocate memory then copy will be nice idea I think, otherwise you may victim of segfault Commented Jul 4, 2013 at 21:23

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.