mardi 30 mai 2017

Can i make the constructor of a derived class contexpr if the base class constructor is not constexpr?

i am trying to compile an example from "Design Patterns" and i am facing the following problem:

i got the base class MapSite:

class MapSite{
    public:
    MapSite();
    virtual ~MapSite(); 
    virtual void Enter() = 0;
};

and the derived class Room:

class Room : public MapSite final{

private:
unsigned int room_number;

public:
Room(unsigned int rn) : room_number(rn) {};

virtual void Enter() override;
};

From another class i want to call the function

virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return make_unique<Room(n)>();} 

So i will get the following error:

error: temporary of non-literal type ‘Room’ in a constant expression
  virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return unique::make_unique<Room(n)>();}

So i thought the problem may be that the constructor has to be constexpr in order to call the constructor of Room from another function, but setting the constructor to:

public:
constexpr Room(unsigned int rn) : room_number(rn) {};

will produce this error:

error: call to non-constexpr function ‘MapSite::MapSite()’
  constexpr Room(unsigned int rn) : room_number(rn) {};

My basic question is whether i can make a derived class constructor constexpr, even if the base class constructor is not.

PS: make_unique is a c++14 feature which i emulated from here How to implement make_unique function in C++11? for c++11, which i am compiling with

Thanks in advance, Lukas!

Aucun commentaire:

Enregistrer un commentaire