Operator Overloading for Smart Pointers

Hi there,

I'm trying to write a smart pointer class for an int variable but I've gotten a little stuck. Firstly, to declare a smart pointer to an int, I MUST use this line of code (As seen in the main method below):

smart_pointer s = new int();

To do this, I try to overload the "=" operator and set a pointer to an int (called "value" in the smart_pointer class) to the address of this new int. However, I get this error for the first line of code in my main method:

"conversion from ‘int*’ to non-scalar type ‘smart_pointer’ requested"

What am I doing wrong? I thought "new int()" returned a memory address which I could set the smart_pointer's int pointer to by overloading the "=" sign...

Thank you.

-------Code-------

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<stdio.h>
#include<stdlib.h>

class smart_pointer{
private:
int *value;

public:
smart_pointer();

// Overwrite "=" operator.
smart_pointer &operator=(int *val){
value = val;
return *this;
}

~smart_pointer(){
delete value;
}
};

smart_pointer::smart_pointer(){
value = NULL;
}

int main(void){
smart_pointer s = new int();
return 0;
} 
closed account (1vRz3TCk)
You actually need to give it a constructor that take a pointer to an int as its argument.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class smart_pointer
{
private:
    int *value;

public:
    smart_pointer(int * pValue)
        : value(pValue)
    {
    }

    ~smart_pointer()
    {
        delete value;
    }

};

int main()
{
    smart_pointer s = new int();
    return 0;
}


You will then need to override operator* and operator->
Oh I see, so smart_pointer s = new int(); calls the constructor of smart_pointer then and not the overloaded "=" operator.

Thank you very much for helping me!
closed account (1vRz3TCk)
yes, smart_pointer s = new int(); does not call the assignment operator (=), it is just different syntax for smart_pointer s(new int());.
@CodeMonkey:
Can we overload the operator->?
I seem to remember we can't!
closed account (1vRz3TCk)
Yes, you can overload operator->, but thinking about it you probably wouldn't need it for an int pointer.
Why not templatize the class? This would be almost as simple as a fixed type class and reusable for multiple types.
Topic archived. No new replies allowed.