Coming from the Java / PHP world, I'm still new to C ++. Some simple things to do in other languages are a little harder to do in C ++.
My main problem is as follows. Right now I have a class (ie, "Something") for which the constructor is introduced with the dependency of a virtual class (ie, children of the "base"). The constructor then saves this entered instance in the class field unique_ptr<Base>
(using the clone idiom). This works well at the application level, everything works as expected. Here is a sample code:
class Base {
public:
virtual std::unique_ptr<Base> clone() = 0;
virtual void sayHello() const = 0;
};
class Something {
public:
explicit Something(Base &base) { this->base = base.clone(); }
void sayHello() const { base->sayHello(); }
private:
std::unique_ptr<Base> base;
};
, , , . , . , "" .
:
class SpyDerived : public Base {
public:
explicit SpyDerived() = default;
SpyDerived(const SpyDerived &original) { this->someState = original.someState; }
std::unique_ptr<Base> clone() override { return std::make_unique<SpyDerived>(*this); }
void sayHello() const override { std::cout << "My state: " << someState << std::endl; }
void setSomeState(bool value) { this->someState = value; }
private:
bool someState = false;
};
, :
int main() {
SpyDerived derived;
Something something(derived);
derived.setSomeState(true);
something.sayHello();
}
someState
false
. , Derived
Something
Derived
, .
, , , Something
SpyDerived
, . . .
MSVC 2015 . , , ++, copy/move .
.