-1

The program is aimed to create a deep copy constructor for Foo. Here's the class definition:

class Foo {
  int _cSize;
  char *_cValues;
  std::vector<int> _iValues;
  double _dValues[100];

public:
  double &dValues(int i) { return _dValues[i]; }
  int &iValues(int i) { return _iValues[i]; }
  char &cValues(int i) { return _cValues[i]; }
  int cSize(void) const { return _cSize; }
  Foo(void) : _cSize(100), _cValues(new char[_cSize]) {}

};

and here's the implementation of copy constructor:

Foo &Foo::operator=(const Foo& foo) {
    _cSize = foo._cSize;
    _cValues = new char [_cSize];
    for (int i = 0; i < _cSize; i++) {
      _cValues[i] = foo._cValues[i];
    }
    _iValues = foo._iValues;
    for (int i = 0; i < 100; i++) {
      _dValues[i] = foo._dValues[i];
    }
    return *this;
}

However, the operator= is showing an error that "Definition of implicitly declared copy assignment operator". Any suggestions on how to fix the copy constructor?

aurora
  • 67
  • 3
  • 3
    You didn't declare `operator=` – jabaa May 07 '22 at 16:52
  • Foo does not declare the assignment operator, thus you are attempting to define the implicit operator. – 273K May 07 '22 at 16:52
  • 1
    Don't use raw pointers. Use `std::string` or `std::vector` instead and you won't have to define the copy operations at all. The compiler will generate deep-copying correct ones automatically. – user17732522 May 07 '22 at 16:52
  • 1
    There is no **copy constructor** shown in this code. The `operator=` in this code is a **copy assignment operator**, not a copy constructor. In fact, the copy assignment operator would be best implemented by using the copy constructor, if one were implemented properly. – Remy Lebeau May 07 '22 at 16:58
  • Further, the *copy-assignment operator* that is shown leaks memory (the original content pointed to by `_cValues`). – WhozCraig May 07 '22 at 17:02

1 Answers1

0

Copy constructors are like

class Foo {
  // ...

  public:
    Foo(const Foo& op) {
      // copy fields
    }
};

note that they are constructors just like Foo(void) you declared, but they have one param that's a const reference.

See also: Copy constructor and = operator overload in C++: is a common function possible?