Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot allocate object of abstract type - but the class is not abstract! (C++)

Tags:

c++

I'm doing a Systems Programming homework. I have to implement a university. I have a Course class, with child classes ComputerScience courses class, PG courses class, and Elective courses class.

class Course
{
public:
    virtual void teach();
    virtual void reg(Student &s)=0;
    std::string getName();
    std::string getDepartment();
    int getSemester();
    int getMinGrade();
    void addStudent(Student *s);
    void removeStudent(Student *s);

protected:
    std::string _department;
    std::string _name;
    int _semester;
    int _minGrade;
    std::vector<Student*> studentsList;  
};

class CSCourse : public Course
{
public:
    CSCourse();
    CSCourse(std::string department, std::string name, int semester, int mingrade);
    ~CSCourse();
    std::string getName();
    std::string getDepartment();
    int getSemester();
    int getMinGrade();
    void addStudent(Student *s);
    void removeStudent(Student *s);
};

(PG courses and Elective courses child classes are the same) In the functions in the Course class (which are not void, like getSemester and such..) I just do dynamic_cast to figure what type of course is it.

I am having this problem:

coursesVector is:

std::vector<Course*> coursesVector

and dp variable is a string containing either CS, PG or Elective. In the main, I do this:

if (dp == "CS")
{
    CSCourse *csCourse = new CSCourse(dp, name, semester, minGrade);
    coursesVector.push_back(csCourse);
}

it gives me "Cannot allocate object of abstract type CS Course". Same goes for PG and Elective!

But, in my definiton of hte class, CS course is not abstract!

like image 369
TheNotMe Avatar asked Dec 16 '25 23:12

TheNotMe


2 Answers

The CSCourse class is abstract.

You have declared a pure virtual function reg in Course, but not provided an implementation in CSCourse.

You compiler undoubtedly told you exactly this as well.

like image 91
John Dibling Avatar answered Dec 19 '25 15:12

John Dibling


You're inheriting from an abstract class which is fine, but you are never implementing the pure virtual function that the base class defines.

Also you need a virtual destructor in your base class;)

Edit: You're also doing other things that probably aren't necessary like redeclaring most of your derived class functions. I bet their implementation is the exact same as your base class?

like image 42
Ryan Guthrie Avatar answered Dec 19 '25 16:12

Ryan Guthrie