Reputation: 31
Consider the following UML:
When I try to implement the virtual function rate()
in Single.cpp
, I get an error: cannot allocate an object of abstract type 'Single'
Booking* b = new Single();
The addBooking()
function should make a pointer of Single
of type Booking
, add the pointer to the QList
(BookingList
derives from QList<Booking*>
) and return the Booking
pointer.
When I comment out the virtual function then everything works. Why is this occurring, and how can I fix it?
Below is a minimal version of my program:
#ifndef BOOKING_H
#define BOOKING_H
class Booking
{
public:
Booking();
double SINGLE_PPPN = 200.00;
virtual double rate() = 0;
};
#endif // BOOKING_H
#include "booking.h"
Booking::Booking()
{
}
#ifndef BOOKINGLIST_H
#define BOOKINGLIST_H
#include <QList>
#include <iostream>
#include "booking.h"
#include "single.h"
using namespace std;
class BookingList : public QList<Booking*>
{
public:
BookingList();
Booking* addBooking();
void deleteAll();
};
#endif // BOOKINGLIST_H
#include "bookinglist.h"
BookingList::BookingList()
{
}
Booking* BookingList::addBooking()
{
Booking* b = new Single();
this->append(b);
cout << "Total bookings: " << this->size() << "\n\n" <<endl;
return b;
}
void BookingList::deleteAll()
{
for (int i = 0; i < this->count(); i++)
{
cout << "Deleting Item At: " << i << endl;
delete this->at(i);
}
}
#ifndef SINGLE_H
#define SINGLE_H
#include "booking.h"
class Single : public Booking
{
public:
Single();
};
#endif // SINGLE_H
#include "single.h"
Single::Single()
{
}
double Single::rate()
{
return Booking::SINGLE_PPPN;
}
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
return a.exec();
}
Upvotes: 0
Views: 145
Reputation: 117876
You need to declare your method override
in the class definition
class Single : public Booking
{
public:
Single();
double rate() override; // this line
};
then you can actually implement the method in your cpp file as you did
double Single::rate()
{
return Booking::SINGLE_PPPN;
}
Upvotes: 2