I am trying to assign a unique_ptr
holding a derived class pointer to a unique_ptr
holding a base class pointer. However, I am receiving the following error:
error: conversion from ‘unique_ptr<GreenStack,default_delete<GreenStack>>’ to non-scalar type ‘unique_ptr<Stack,default_delete<Stack>>’ requested
Code snippet is below.
class GreenStack;
class Stack {
public:
explicit Stack(double initial_weight) : weight_(initial_weight) {}
static std::unique_ptr<Stack> makeGreenStack(double initial_weight)
{
//std::unique_ptr<Stack> box = std::make_unique<Stack>(initial_weight);
std::unique_ptr<Stack> green_box_01 = std::make_unique<GreenStack>(initial_weight);
return std::move(green_box_01);
}
bool operator<(const Stack& rhs) const { return weight_ < rhs.weight_; }
virtual ~Stack() = default;
protected:
double weight_;
};
class GreenStack:public Stack
{
public:
explicit GreenStack(double initial_weight): Stack(initial_weight){}
~GreenStack() = default;
};
Please guide to resolve this error.
CodePudding user response:
Define Stack::makeGreenStack(double)
after defining GreenStack
to be derived from Stack
.
The compiler will then know that a std::unique_ptr<Stack>
can be initialized from a std::unique_ptr<GreenStack>
class GreenStack;
class Stack {
public:
explicit Stack(double initial_weight) : weight_(initial_weight) {}
static std::unique_ptr<Stack> makeGreenStack(double initial_weight);
bool operator<(const Stack& rhs) const { return weight_ < rhs.weight_; }
virtual ~Stack() = default;
protected:
double weight_;
};
class GreenStack:public Stack
{
public:
explicit GreenStack(double initial_weight): Stack(initial_weight){}
~GreenStack() = default;
};
std::unique_ptr<Stack> Stack::makeGreenStack(double initial_weight)
{
std::unique_ptr<Stack> green_box_01 = std::make_unique<GreenStack>(initial_weight);
return green_box_01;
}