tyhenry tyhenry - 3 months ago 45
C++ Question

c++ initializer list issue - error: attempting to reference a deleted function

I'm using VS (2015) in c++ for the first time, and am a newbie at creating halfway decent code. Trying to do something simple - use an initializer list... but it's throwing this error: "C2280: attempting to reference a deleted function"

I have (User.h):

class User {
protected:
ICoordinateMapper* _coordMapper;
public:
User(ICoordinateMapper coordinateMapper)
: _coordMapper(coordinateMapper){}
};


If I overload the constructor as follows, it runs fine:

class User {
protected:
ICoordinateMapper* coordinateMapper;
public:
User(){}
User(ICoordinateMapper* coordinateMapper)
: _coordMapper(coordinateMapper){}
};


My app is run (through openFrameworks) as:

#include "ofApp.h"
int main(){
...
ofRunApp(new ofApp());
}


ofApp.h:

#pragma once
#include "ofMain.h"
#include "User.h"
class ofApp : public ofBaseApp{
public:
...
User user;
}


Why is that? I thought I didn't need to overload the constructor when using initializer lists? Or do I?

Answer

In the first variant, where you don't have a User default constructor, the compiler will not create a default constructor for you. That means there is no way to default-construct (like you do in the ofApp class) an object of the User class.

There are two ways of solving the problem: The first one you already know and that is to create a default constructor. As a variant of this you could use the compilers default constructor by using

class User {
  ...
  User() = default;
  ...
};

The other solution is to use default arguments for the other constructor, so it can be invoked without arguments like a default constructor:

class User {
  ...
  User(ICoordinateMapper coordinateMapper = nullptr)
    : _coordMapper(coordinateMapper){}
  ...
};

I would recommend the second way, as it will initialize the _coordMapper member.

Comments