-2

I have recently started learning OOP in C++ and I started solving example tasks regarding it. I want to instantiate an object of the class CStudent after having created a default constructor for it. However the compiler cannot compile the code. I would like to ask why is that?

A.Petrov
  • 1
  • 2
  • 2
    Please always include the error message. – Davide Spataro Jun 29 '18 at 10:01
  • 2
    You **declared** a constructor, you need to **define** it, or let the compiler define it for you using `= default`. – Holt Jun 29 '18 at 10:01
  • If you change `CStudent();` to `CStudent() = default;`, you could even force the compiler to implement the constructor for you. `CStudent() { }` would do as well. In both cases, the compiler will use the default constructors for all members. – Scheff's Cat Jun 29 '18 at 10:21
  • @Scheff It would actually use the default member initializer for `name` ;) – Holt Jun 29 '18 at 10:21
  • Off-topic: You should avoid `using namespace std;` at such a global scope, see https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – Holt Jun 29 '18 at 10:22
  • @Holt You are right - I oversaw this detail. – Scheff's Cat Jun 29 '18 at 10:22

2 Answers2

3

When you write inside your class:

CStudent();
CStudent(string name, string fn);

...you only declare two constructors, one default (taking no-argument) and one taking two strings.

After declaring them, you need to define them, the same way you defined the methods getName or getAverage:

// Outside of the declaration of the class
CStudent::CStudent() { }

// Use member initializer list if you can
CStudent::CStudent(std::string name, string fn) : 
    name(std::move(name)), fn(std::move(fn)) { }

In C++, you can also define these when declaring them inside the class:

class CStudent {
// ...
public:
    CStudent() { }
    CStudent(std::string name, string fn) : 
        name(std::move(name)), fn(std::move(fn)) { }
// ...
};

Since C++11, you can let the compiler generate the default constructor for you:

// Inside the class declaration
CStudent() = default;
Holt
  • 36,600
  • 7
  • 92
  • 139
0

This should work, As commented by Holt, You need to define constructor, You have just declared it.

#include <iostream>
#include <string>
#include <list>
using namespace std;
class CStudent {
    string name = "Steve";
    list<int> scores;
    string fn;

public:
    CStudent() {};
    CStudent(string name, string fn);
    string getName();
    double getAverage();
    void addScore(int);
};
string CStudent::getName() {
    return name;
}
double CStudent::getAverage() {
    int av = 0;
    for (auto x = scores.begin(); x != scores.end(); x++) {
        av += *x;
    }

    return av / scores.size();
}
void CStudent::addScore(int sc) {
    scores.push_back(sc);
}

int main()
{
    CStudent stud1;
    cout<< stud1.getName()<< endl;


    return 0;
}
yadhu
  • 1,253
  • 14
  • 25