'C++ overload assignment operator
I'm currently struggling with the assignment operator. I keep missing something. Could you help me out here?
Check it out here https://godbolt.org/z/rfvTqcjoT
class SpecialFloat
{
public:
explicit SpecialFloat(const float f);
SpecialFloat& operator=(const float f);
private:
float m_float;
};
SpecialFloat::SpecialFloat(const float f):
m_float(f)
{
}
SpecialFloat& SpecialFloat::operator=(const float f)
{
m_float = f;
}
int main()
{
SpecialFloat f = 1.0f;
}
why is my operator overloading not working?
<source>(27): error C2440: 'initializing': cannot convert from 'float' to 'SpecialFloat'
<source>(27): note: Constructor for class 'SpecialFloat' is declared 'explicit'
or can the assignment operator not take custom types?
Solution 1:[1]
There are couple of issues as below.
SpecialFloat f = 1.0f;
Means you are trying to assign a float value to a SpecialFloat object. This works if constructor of SpecialFloat takes a float argument and if the constructor is not marked as explicit. But in your code, you marked the constructor as explicit. So object is not getting created and throwing error. If you want to know more about explicit constructor, read What does the explicit keyword mean?
Assignment operator overload function should return SpecialFloat object. You are not returning any thing which is wrong. It should return SpecialFloat object as below.
SpecialFloat& SpecialFloat::operator=(const float f)
{
m_float = f;
return *this;
}
Your understanding about assignment operator overloading function call is wrong. Assignment operator overloading function will be called when you are trying to assign an object to already created object.
SpecialFloat f = 1.0f;
Above statement is trying to create an object. So Assignment operator overloading function won't be called in this case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kadina |
