"Cannot allocate an object of abstract type" error
Asked Answered
R

2

33

Error is here:

vector<Graduate *> graduates;
graduates.push_back(new AliceUniversity(identifier,id,salary,average));

Grandparent class:

Graduate::Graduate(char identifier,
                   long id,
                   int salary,
                   double average)
    : _identifier(identifier),
      _id(id),_salary(salary),
      _average(average)
{
}

Parent class:

UniversityGraduate::UniversityGraduate(char identifier,
                                       long id,
                                       int salary,
                                       double average)
    : Graduate(identifier,id,salary,average)
{
}

Actual/child class:

AliceUniversity::AliceUniversity(char identifier,
                                 long id,
                                 int salary,
                                 double average)
    : UniversityGraduate(identifier,id,salary,average)
{
    _graduateNum++;
    _sumOfGrades += average;
    _avrA = getAverage();
}

I know it's a long shot, I cant write the entire code here…

Radioscopy answered 8/9, 2011 at 18:23 Comment(2)
This isn't going to do - post real code, and in particular places where you declare pure virtual functions (look for = 0;).Ruthannruthanne
the constructors are completely irrelevant, you should have posted the declarationsHatteras
F
85

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

Federicofedirko answered 8/9, 2011 at 18:25 Comment(1)
//You can not create objects of that class, but may only have pointers or references to it.// Is that correct?Drayman
R
17

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

Rigamarole answered 8/9, 2011 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.