What you are looking for is run-time polymorphism, which means that the object takes "many forms" (i.e. a or b) and acts accordingly as the program launches. In C ++, you do this by creating a virtual function in the base class a :
virtual void print() {cout << "hello"};
Then you need to save the elements by pointer or link, and, as a rule, derived classes can introduce new data members and need more memory - this is normal for creating objects on the heap with new :
a* blah[10]; blah[5] = new b();
Then you can call:
blah[5]->print();
And he will choose b implementation of print() .
You should delete blah[5] later (and any other pointer to the memory returned by new ).
In practice, it is useful to use a container that can remove the objects that it contains when it is destroyed, due to the fact that it left the area or was deleted. std::vector<> is one such container. You can also use smart pointers to automate the deletion of objects a and b . This helps make the code correct if exceptions are thrown before executing delete , and you want your program to continue to run without memory leak. The acceleration library is the easiest / best place to implement a smart pointer. Together:
#include <vector> #include <boost/shared_ptr.hpp> std::vector<boost::shared_pointer<a> > blah(10); blah[5] = new b();
(It is more natural to use vectors with push_back() , since it automatically generates a vector so that it fits all the elements you added with the new general accessibility by calling vector::size() .)
Tony delroy
source share