Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an assignment (=) operator for class in C++ [duplicate]

Tags:

c++

Possible Duplicate:
Operator overloading

EDIT 2

I was using insert(...) incorrectly, I didn't actually need a '=' operator. Sorry to waste peoples' time. I have voted to close.. 2 votes remain. Please vote.

EDIT

The reason I want an '=' operator is so I can use the insert(...) function on a vector of Derivation objects. At the moment my compiler says:

/usr/include/c++/4.2.1/bits/stl_algobase.h:283: error: no match for 'operator=' in '* __result = * __first'

I have created '==' and '<' operators for my own classes before but I'm struggling to create an '=' operator. My class looks like this (ignore the silly variable names):

class Derivation {
public:
    string                  rc; 
    ImplementationChoice    Y; 
    vector<Derivation>      X;
    vector<string>          D;       
    vector<string>          C;       
    vector<Player>          P, O;   
    vector<Attack>          B;   

    // various functions
    // ...
};

and I want to know what I need to put in

// What do '=' return?  An object of the class right?
Derivation& operator=(const Derivation &d) const {
    // something....
}

Many thanks.

like image 489
ale Avatar asked Jul 18 '11 13:07

ale


People also ask

Can you use an assignment operator (=) to copy one object to another object of a same class?

The assignment operator (operator=) is used to copy values from one object to another already existing object. The purpose of the copy constructor and the assignment operator are almost equivalent -- both copy one object to another.

Can you use an assignment operator (=) to copy one object to another object of a same class if yes how if not why not?

You cannot use the = operator to assign one object's values to another object, unless you overload the operator.

How do you define copy assignment operator?

A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&. For a type to be CopyAssignable, it must have a public copy assignment operator.

Is == an assignment operator?

The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not.


1 Answers

First, an assignment operator probably should not be const--

Second, assignment operators usually return a non-const reference to the object that was assigned a value (*this)

like image 150
antlersoft Avatar answered Oct 27 '22 00:10

antlersoft