#include <iostream>

template<typename T>
struct Cloneable
{
	virtual T *Clone() const
	{
		return new T(*dynamic_cast<const T*>(this));
	}
protected:
	Cloneable(){}
	Cloneable(const Cloneable &){}
	virtual Cloneable &operator=(const Cloneable &){ return*this; }
	virtual ~Cloneable(){}
};

struct A : Cloneable<A>
{
	A() : x(1) {}
	A(const A &f) : x(f.x) {}
	A(int v) : x(v) {}
	virtual A &operator=(const A &f)
	{
		x = f.x;
		return*this;
	}

	virtual A *Clone() const = 0;
	virtual void Print() const
	{
		std::cout << "x=" << x << std::endl;
	}

	virtual ~A(){}
private:
	int x;
};

struct B : A, Cloneable<B>
{
	B() : q(2) {}
	B(const B &f) : A(f), q(f.q) {}
	B(int v) : A(v-1), q(v) {}
	virtual B &operator=(const B &f)
	{
		A::operator=(f);
		q = f.q;
		return*this;
	}
	virtual A &operator=(const A &f)
	{
		A::operator=(f);
		const B *b = dynamic_cast<const B*>(&f);
		if(b)
		{
			q = b->q;
		}
		return*this;
	}

	using Cloneable<B>::Clone;
	virtual void Print() const
	{
		std::cout << "q=" << q << ", ";
		A::Print();
	}

	~B(){}
private:
	int q;
};

int main()
{
	B b1 (7), b2, *b3 (0);
	A &a1 (b1), &a2 (b2), *a3 (0);

	b1.Print();
	b2.Print();

	a1.Print();
	a2.Print();

	b3 = b1.Clone();
	b3->Print();
	delete b3;

	a3 = a1.Clone();
	a3->Print();
	delete a3;

	b2 = b1;
	b2.Print();

	a3 = new B(9);
	a2 = *a3;
	a2.Print();
	b2.Print();
}