2

I keep getting this error when compiling, but I don't know why. I have looked at this post and this one, but they appeared to be different problems.

The relavent code structure is:

// main.cpp

#include "MyClass.h"

int main() {
    MyClass newClass = MyClass();
}


// MyClass.h

#include <string>
#include <sstream>
#include <vector>
using namespace std;
class Node;

class MyClass {
private:
    vector<Node*> nodes;
    int number;
    stringstream fileInfo;
public:
    MyClass();
    ~MyClass();
};


// MyClass.cpp

#include "MyClass.h"

MyClass::MyClass() {
    number = 1;
}

MyClass::~MyClass() {}

The error I get when compiling is:

main.cpp: In function 'int main()':
main.cpp:4:29: error: use of deleted function 'MyClass(const MyClass&)'
  MyClass new Class = MyClass();
                              ^
In file included from main.cpp:1:0:
MyClass.h:7:7: note: 'MyClass::MyClass(const MyClass&)' is implicitly deleted because the definition would be ill-formed:
  class MyClass {
        ^
MyClass.h:7:7: error: use of deleted function 'std::__cxx11::basic_stringstream<_CharT, _Traits, _Alloc>::basic_stringstream(const std::__cxx11:basic_stringstream<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
In file included from MyClass.h:2:0,
                 from main.cpp:1:
/usr/included/c++/5/sstream:721:7: note: declared here
        basic_stringstream(const basic_stringstream&) = delete;
        ^

I have tried initializing all the class members in the constructor, but that didn't change the error. Other than that I can't think of what is wrong.

Jacob Bischoff
  • 126
  • 1
  • 12

1 Answers1

2

The problem is that your class is not copy-able because it contains a std::stringstream (which is itself not copy-able). This results in its copy constructor being deleted, which is what the compiler is trying to tell you. To fix this, simply don't use the copy-initialization syntax in your main function.

int main() {
  MyClass newClass;
}
Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58