we are trying to implmenent a solution with abstract superclass in C++: Control is the super class of Spline and others. Now when we try to instantiate an object of type Spline the instantiation fails with two errors:
- cannot find method with matching parameters for the constructor of class Spline
- cannot allocate an object of abstract type 'Control'
How can we fix those issues?
Instantiate Spline of type Control and use it in main:
RampFunction timeRampFn{0, 100, 2000, 1000};
RampFunction distanceRampFn{0, 0, 0.5f, 1000};
Control ctrl = new Spline(slowDownCoeff, timeRampFn, distanceRampFn);
ctrl.calculateAction(&newRobotState, p_0, p_t, targetTrack, timeFromStart, distanceToTarget);
Control.hpp (abstract super class):
#ifndef CONTROL_HPP
#define CONTROL_HPP
#include <vector>
#include <Data/Track.h>
#include <Data/TrackPoint.h>
#include <Data/RobotState.h>
#include <boost/multiprecision/eigen.hpp>
using Eigen::Vector2f;
using namespace std;
class Control
{
private:
const float FUTURE_INTERVAL = 0.1f;
protected:
const int FUTURE_SIZE = 10;
public:
virtual void calculateAction(RobotState *state, Vector2f curPos, Vector2f refPos, Track targetTrack, float timeFromStart, float distanceToTarget) = 0;
};
#endif
Spline.hpp:
#ifndef SPLINE_HPP
#define SPLINE_HPP
#include <Control/Control.hpp>
using Eigen::Vector2f;
using namespace std;
class Spline : Control
{
private:
struct RampFunction
{
float x_0, val_0;
float x_e, val_e;
};
float slowDownCoeff;
RampFunction timeRampFn;
RampFunction distanceRampFn;
public:
Spline(float slowDownCoeff, RampFunction timeRampFn, RampFunction distanceRampFn)
{
this->slowDownCoeff = slowDownCoeff;
this->timeRampFn = timeRampFn;
this->distanceRampFn = distanceRampFn;
}
virtual void calculateAction(RobotState *state, Vector2f curPos, Vector2f refPos, Track targetTrack, float timeFromStart, float distanceToTarget);
};
#endif
Control ctrl = ...
You have created a variable of type Control
. This is not allowed because Control
is an abstract type. This is why you get the error cannot allocate an object of abstract type 'Control'
.
Another problem would be that Control
doesn't have a constructor that would take an argument of type Spline*
.
What you may have been trying to do is to create a base pointer to the derived object: Control* ctrl = ...
. However, this would make deleting the dynamic allocation problematic, since you aren't allowed to delete through the base pointer because the destructor of the base is non-virtual. A solution is to declare the destructor virtual.
But simply making deletion allowed is not sufficient. You should actually perform the deletion or else the memory may leak.