Ensign Variable
Ensign Variable

Reputation: 77

C++ Inheritance - Running Parent Method in Child Class

My parent class, Course, has the method addStudent(Student s). My child class, BetterCourse, inherits from Course. Every time I try to run BetterCourse.addStudent(s), I get the following error:

error: no matching function for call to ‘BetterCourse::addStudent(Student (&)())’ note: candidates are: void Course::addStudent(Student)

I understand it's telling me addStudent() hasn't been defined in BetterCourse and that it's recommending I use the one present in the parent class, Course. This has me confused as the whole idea around inheritance is not needing to redefine inherited functions and variables.

Course is as follows:

#include <iostream>
#include <string>
#include "Student.h"

using namespace std;

class Course
{

    protected:
        string id;
        string name;

    public:
        Course();
        Course(string id, string name);     
        void addStudent(Student s);
};

Course::Course()
{
   //code
}

Course::Course(string id, string name)
{
   //code
}

void Course::addStudent(Student s) 
{
   //code
}

BetterCourse:

#include <iostream>
#include <string>
#include "Course.h"

using namespace std;

class BetterCourse : public Course
{
    public:
        BetterCourse(string id, string name) : Course(id,name){};
};

Upvotes: 3

Views: 999

Answers (3)

PiotrNycz
PiotrNycz

Reputation: 24382

From your error it seems that you for the first time get to the ugliest part of C++.

This:

Student s();

Is function declaration - not object definition. s type is Student (*)() so when you call:

BetterCourse bc; 
bc.addStudent(s);

You get your error - you don't have method to add functions returning Student.

Define Student in the following ways:

Student s;
Student s {}; // new C++11 way
Student s = Student(); // 

Upvotes: 4

Adrian Herea
Adrian Herea

Reputation: 658

you can not call BetterCourse.addStudent(s) you should create an object

BetterCourse obj;
obj.addStudent(s);

should work

If you want to call BetterCourse::addStudent(s) than declare addStudent(s) as static method

Upvotes: 0

jason.zissman
jason.zissman

Reputation: 2800

It sounds like you're actually calling the function 'addStudent' with an inappropriate argument. Could you show the code that is actually calling addStudent on the BetterCourse object? It sounds like you're using a reference to the student instead of the student object itself.

Upvotes: 0

Related Questions