Search code examples
c++constructorcompiler-errorsmost-vexing-parse

Visual C++: No default constructor


I've looked at a couple other questions asking this, but mine seems to be a lot simpler of a case then the ones I've been through, so I'll ask my case for this.

Learn.h:

#ifndef LEARN_H
#define LEARN_H

class Learn
{
public:
    Learn(int x);
    ~Learn();

private:
    const int favourite;
};

#endif

Learn.cpp:

#include "Learn.h"
#include <iostream>
using namespace std;

Learn::Learn(int x=0): favourite(x)
{
    cout << "Constructor" << endl;
}

Learn::~Learn()
{
    cout << "Destructor" << endl;
}

Source.cpp:

#include <iostream>
#include "Learn.h"
using namespace std;

int main() {
    cout << "What's your favourite integer? "; 
    int x; cin >> x;
    Learn(0);

    system("PAUSE");
}

The above code in itself does not output any error.

However, I do get a couple errors after I replace Learn(0) with Learn(x). They are:

  • Error E0291: no default constructor exists for class Learn
  • Error C2371: 'x' : redefinition; different basic types
  • Error C2512: 'Learn' : no appropriate default constructor available

Any reason for this? I really want to actually input the integer variable x inside it rather than the 0. I know this is only practice and I'm new to this, but really, I'm a little confused as to why this doesn't work.

Any help would be appreciated, thanks.


Solution

  • Parsing issue:

    Learn(x);
    

    is parsed as

    Learn x;
    

    You should use

    Learn{x};
    

    to build your temporary or

    Learn some_name{x};
    //or
    Learn some_name(x);
    

    if you want an actual object.