Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi all,
i want to write an operator overloaded function for = operator in VC++. how can i write. can anybody please tell me the syntax of operator overloading in vc++. i need an urgent help..please help me..
Posted
Comments
Legor 1-Jun-11 3:22am    
Plenty of explanations can be found in the internet.

 
Share this answer
 
Comments
Niklas L 1-Jun-11 3:55am    
Actually, I would not recommend that page, since the implementation doesn't check for self-assignment, where the execution would be undefined.
More on "self-assignment",
http://www.parashift.com/c++-faq-lite/assignment-operators.html
Niklas L 1-Jun-11 5:14am    
Good link!
 
Share this answer
 
(Uncompiled) example with a class containing an array of ints:
C++
class A
{
    int *_ptr;
    int _count;

    A& operator=(const A& rhs)
    {
        if (this != &rhs)
        {
            // Clean-up of this
            delete _ptr;

            // Assinment here
            _count = rhs._count;
            _ptr = new int[_count];

            std::copy(rhs._ptr, &rhs.ptr[_count], _ptr);
        }

        return *this;
    }
};

The fact that you return a non-const reference allows for a bit awkward usage:
C++
A a1, a2, a3;
(a1 = a2) = a3;

IMHO returning a const reference would be a better choice, even though it would not conform to the built in types.

Note how it's needed to avoid self assignment in this case. If we did not check for self-assignment, the clean-up part of the method would destroy the data before we had a chance to copy it.
 
Share this answer
 
Comments
Perfect Example with member pointers.5ed
Niklas L 1-Jun-11 5:14am    
Thank you!
Stefan_Lang 1-Jun-11 5:28am    
Perfect, 5!
Maybe you should add an explanation for the use of std::copy though - someone asking for the syntax of an assignment operator may not be familiar with that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900