user2036212
user2036212

Reputation: 37

Enforce assignment operator instead of copy constructor on initialization?

I'm putting together my own (silly) Scalars/List/Hash (perl-like..) thing in C++.

I've come across a point having to dereference a Scalar into a List, and it does not work when attempted in initialization.

List several default constructors, out of which 5 range from List() to List(Scalar, Scalar, Scalar, Scalar).

List stuff(1, 2, 3);
Scalar aref = stuff; // List overloads the (Scalar) cast operator

// the following line is the unwanted thing..
List failist = aref; // uses List::List(Scalar), so same as `List failist(aref);`

// however, these work
List thisworks;
thisworks = aref;
thisworks.operator=(aref);

List header:

class List : public Thing {
    std::vector<Scalar> stuff;
public:
    List();
    List(Scalar s1); // this gets called because initialization
    List(Scalar s1, Scalar s2);
    List(Scalar s1, Scalar s2, Scalar s3);
    List(Scalar s1, Scalar s2, Scalar s3, Scalar s4);
    List &operator=(const Scalar &other); // but i want this

    /* some getters/setters cut away */

    operator Scalar();
};

I'd really like to use List mylist = listreference;, how do I ?

Upvotes: 0

Views: 446

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

I'm wondering if you don't want List myList = scalar to invoke the constructor, then why do you have it in the first place?

Anyway, make it explicit as :

explicit List(Scalar s1);. 

That way, you would make the compiler to spit out error on line:

List myList = scalar; //error 

and then you will have chance to correct yourself, either by writing:

List myList(scalar); //ok

Or,

List myList; 
myList = scalar; //ok

Note that you cannot make List myList = scalar to invoke List& operator=(Scalar const&), you can however implement one in terms of other, or both in terms of some common init function to avoid code duplication. The latter approach is better.

Upvotes: 2

ixSci
ixSci

Reputation: 13698

You can't do it. List mylist = listreference; means: create mylist object of type List with copy constructor. So you have 2 options:

  1. Implement copy constructor via opeartor=
  2. Do it with two lines of code: List mylist = listreference; mylist = listreference;

Upvotes: 1

Related Questions