Osama Kawish
Osama Kawish

Reputation: 390

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:

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.

Upvotes: 2

Views: 1965

Answers (3)

Jake
Jake

Reputation: 637

I had similar code and came up with a different errors because I was compiling with Linux in a terminal. My errors were:

error: conflicting declaration 'myObject str' 
error: 'str' has a previous declaration as 'const string  str'

when I tried myObject(str);

Sure Learn{x}; (and in my case myObject{str};) will successfully compile, but it creates a temporary object, then destroys it in the same line.

This is not what I wanted to do. So an alternative solution is to create a new object like:

Learn var_name = new Learn(x);

This way you can reference it for future use.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217245

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.

Upvotes: 8

Osama Kawish
Osama Kawish

Reputation: 390

Okay, I figured out the problem I was having. I didn't realize that the call is done as part of an object assignment. The notation in C++ seems to be a bit different that way.

So Learn(x) should be replaced with Learn obj(x) apparently.

This notation is a little off from other programming languages where you can usually write className(inputs) variableName.

Upvotes: 0

Related Questions