Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- class A
- {
- protected:
- virtual int Add() { cout << "Hello"; }
- public:
- void Dec() { cout << "\n"; }
- private:
- int a;
- };
- class B : public A
- {
- public:
- virtual int Add(int a) { A::Add(); cout << " World"; }
- };
- class C : public A
- {
- public:
- virtual int Add() { cout << "!"; }
- };
- // ==================================================
- class Factory
- {
- public:
- Factory() {}
- public:
- A* CreateObject(int a)
- {
- if (a == 0)
- return new B();
- else if (a == 1)
- return new C();
- }
- };
- // ==================================================
- int main(void)
- {
- Factory f;
- B *b = dynamic_cast<B*>(f.CreateObject(0));
- C *c = dynamic_cast<C*>(f.CreateObject(1));
- b->Add(5);
- c->Add();
- b->Dec();
- c->Dec();
- c->Add();
- delete c;
- delete b;
- // --------------------------------------
- cout << endl << "=====================================" << endl << endl;
- B* arrB[3];
- arrB[0] = dynamic_cast<B*>(f.CreateObject(0));
- arrB[1] = dynamic_cast<B*>(f.CreateObject(1)); // <----| ???
- arrB[2] = dynamic_cast<B*>(f.CreateObject(0));
- //arrB[1]->Add(4); // error?
- delete arrB[0];
- delete arrB[1];
- delete arrB[2];
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment