How can I override the assignment operator for my class to allow for the assignment as 0 (or NULL)?

Jul 7, 2011 at 7:13pm
so i can do something like:
1
2
class myclass{//yadayadayada}myinstanceofmyclass;
myinstanceofmyclass = 0;


I'm getting error message.

this is what i have so far as my = operator.

1
2
3
4
5
myclass &operator=(const myclass &r)
     {
         data = r.data;
     }


Data is a string variable.

Can I do:

 
myclass & operator=(NULL)//yadayada 


or

 
myclass & operator=(0)//etcetcetc 
?
Jul 7, 2011 at 7:29pm
you can give anything which can implicitly be casted to myclass. Depends on the constructors you have in your class.

so if you are getting error, the data is not able to implicitly converted to your class.
Jul 7, 2011 at 7:36pm
well I have this:
1
2
3
4
    myclass(const myclass & m) //copy constructor
    {
        data = m.data;
    }


Would that suffice?

As it is now, the error I am getting is
error: conversion from 'int' to non-scalar type myclass requested
Last edited on Jul 7, 2011 at 7:36pm
Jul 7, 2011 at 7:55pm
Yes, because this:
myinstanceofmyclass = 0;
requires construction of myclass from int, i.e. the following operator:
myclass& operator= (int);
However, all the compiler can find is:
myclass &operator=(const myclass &r);
Thus it tries to convert int to const myclass&, which fails. Hence the error:
error: conversion from 'int' to non-scalar type myclass requested


If you want to assign an integer to an instance of your class, then write an operator accordingly. It will, of course, also allow assignment of nonzero integers.
Jul 7, 2011 at 8:00pm

see this and try writing =operator and other constructors.

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
class myclass
{

private:
	char *m_data;	
	int m_len;

public:
	
	myclass()
	{
		m_data = 0;
	}

	myclass(int i)
	{
		if(i)
		{
			m_len = i;
			m_data = new char[m_len];	
		}		
	}

	~myclass()
	{
		if(m_len)
			delete m_data;
	}
};



myclass m = 0; //this will work.
Jul 7, 2011 at 8:21pm
thanks I got the idea now.
Topic archived. No new replies allowed.