Search code examples
c++assignment-operator

throw assignment operator


C++

How do I throw an error when someone calls the assignment operator?

I have a base class that uses a factory method instead of a constructor. The factory methods reads a file and calls the derived class constructor based on the file contents.

Base *a::create(file1);
Base *b::create(file2);

I want to throw an error if someone calls the assignment operator.

*a = *b; // filetype contents don't match

At this moment when the above is executed, my *a's contents are overwritten by *b. I'm assuming its calling the implicit assignment operator, which is what I don't want to happen.

When I declare the assignment operator private. I get the following errors when I run it in a separate test file.

test.cc:34:13: fatal error: 'operator=' is a private member of 'Test'
    *aa = *ad;
    ~~~ ^ ~~~
./Base.h:14:16: note: declared private here
    Base& operator=(const Base &rhs);
           ^
1 error generated.
make: *** [test] Error 1

I would like it to rather throw an error instead of what is shown above. Like "you can't do this" or something.

Any help would be appreciated.


Solution

  • Compile time errors are better than runtime ones (because they prevent the developer from thinking their code might work when it actually has no chance). The right thing to do is declare the unusable operators and constructors as private or protected, so that they cannot be used except by friends (e.g. factories).