1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <iostream>
using namespace std;
class Base{
protected:
Base() { }
public:
virtual ~Base() {}
virtual void ToCout() = 0;
};
class A : public Base {
public:
A(int a) : _a(a) { cout << "creation A " << endl; }
A(const A& a) : _a(a._a) { cout << "creation A " << endl; }
virtual ~A() { cout << "destruction A " << endl; }
virtual void ToCout() override {
cout << "A a = " << _a << endl;
}
int _a;
};
class B : public Base {
public:
B(int a, int b) : _a(a), _b(b) { cout << "creation B " << endl; }
B(const B& b) : _a(b._a), _b(b._b) { cout << "creation B " << endl; }
virtual ~B() { cout << "destruction B " << endl; }
virtual void ToCout() override {
cout << "B a = " << _a << " b = " << _b << endl;
}
int _a;
int _b;
};
template <typename T>
T* copy(T* source)
{
return new T(*source);
}
int main()
{
{
cout << endl << "instance * -> copy sur b avec abstraction" << endl;
Base* a = new B(20, 30);
//Base* b = copy(a); // la ca marche pas
Base *b = copy(dynamic_cast<B*>(a));
cout << "pointeur a = 0x" << a << " b = 0x" << b << endl;
((B*)b)->_a = 50;
((B*)b)->_b = 60;
cout << "instance A = "; a->ToCout();
cout << "instance B = "; b->ToCout();
delete a;
delete b;
}
return 0;
} |
Partager