#include <iostream>
#include <memory>
struct Base;
typedef std::unique_ptr<Base> BasePtr;
struct Base
{
protected:
// Kopierverbot.
Base(const Base&) = default;
Base& operator=(const Base&) = default;
public:
Base(int common):common(common) {}
int common = 0;
// das "operative" Interface meiner Ableitungen
virtual void behavior() = 0;
// polymorph clonen
virtual BasePtr clone() = 0;
// nur als Debug-Hilfe
virtual void info() { std::cout << "Base int common: " << common << std::endl;;}
};
struct TypeA: Base
{
TypeA(int common, int value):Base(common),value(value){}
int value = 0;
virtual void behavior()
{
common += 2;
value *= 2;
};
virtual BasePtr clone() { return BasePtr(new TypeA(*this)); }
virtual void info()
{
Base::info();
std::cout << "TypeA int value: " << value << std::endl;;
}
};
struct TypeB: Base
{
TypeB(int common, double value):Base(common),value(value){}
double value = 0.0;
virtual void behavior()
{
common += 2;
value *= 2.0;
};
virtual BasePtr clone() { return BasePtr(new TypeB(*this)); }
virtual void info()
{
Base::info();
std::cout << "TypeB double value: " << value << std::endl;;
}
};
void CloneAndReassigne(BasePtr& original)
{
std::cout << "CloneAndReassigne" << std::endl;
BasePtr clone = original->clone();
std::cout << "Original:" << std::endl;
original->info();
clone->behavior();
std::cout << "Clone nach Aenderung:" << std::endl;
clone->info();
// *original = *clone; compiliert nicht mehr. Stattdessen:
original = clone->clone();
std::cout << "Original nach Aenderung:" << std::endl;
original->info();
}
int main()
{
BasePtr a(new TypeA(1, 2));
BasePtr b(new TypeB(2, 4));
CloneAndReassigne(a);
CloneAndReassigne(b);
}