Home Articles Books Downloads FAQs Tips

What's Wrong With This Code? Volume #1


The assignment operator

Experienced programmers will tell you that most C++ classes should contain, at a minimum, a default constructor, a copy constructor, an assignment operator, and a destructor. The following code example contains a class called Foo that attempts to follow these guidelines. The code also contains a factory method called GetAFoo, whose sole purpose is to create and return new Foo objects.

#include <iostream>

using namespace std;

class Foo
{
public:
    Foo()
    {
        cout << "default constructor" << endl;
    }

    Foo(const Foo &)
    {
        cout << "copy construction" << endl;
    }

    ~Foo()
    {
        cout << "destructor" << endl;
    }

    Foo& operator=(Foo &rhs)
    {
        cout << "assignment" << endl;
        return *this;
    }
};


Foo GetAFoo()
{
    Foo foo;
    return foo;
}


int main()
{
    Foo foo1;
    Foo foo2;
    foo1 = GetAFoo();   // generates compiler error
    foo2 = foo1;        // compiles OK
    return 0;
}

Notice that the Foo class provides a default constructor, a copy constructor, a destructor, and an assignment operator. Despite our best intentions, the code contains a couple of problems. First and foremost, it does not compile. The compiler error is:

[C++ Error] broken.cpp(43):
E2285 Could not find a match for 'Foo::operator =(Foo)'.

The Foo class clearly provides an assignment operator that allows you to assign one Foo object to another. But the compiler complains that it can't find an assignment operator for the assignment to foo1. This seems strange, since the assignment to foo2 compiles fine. So what's the difference between the two? Can you find the problem and fix the code so it compiles without error?

In addition to fixing the compilation error, see if you can streamline the code a little bit. There are at least two places where you could improve the runtime performance of the program by making only minor changes to the source.


Answer



Copyright © 1997-2002 by Harold Howe.
All rights reserved.