dimanche 21 janvier 2018

Confusing about the interface in C++ (invalid new-expression of abstract class type)

I defined an interface in my c++ project, and it looks like this:

class PriceInterface
{
public:
    virtual float calculator(float &price, float &weight)=0;
};

And the derivate class defined like this: In header:

class BelgiumPrice:public PriceInterface
{
public:
    BelgiumPrice();
    float calculator(float &price, float &weight) ;
};

And in cpp:

BelgiumPrice::BelgiumPrice()
{

}

float BelgiumPrice::calculator(float &price, float &weight)
{
    if (weight > 5.0f)
        price += (weight - 5.0f)*1.25f;
    return price;
}

I do know I can't instantiate an abstract class, so I used it like this:

std::shared_ptr<PriceInterface> bel = std::make_shared<BelgiumPrice>();

But it gave me the following error:

/usr/include/c++/7/ext/new_allocator.h:136: error: invalid new-expression of abstract class type ‘PriceInterface’
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Can you give me any ideas about this? Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire