Re: factoring book question and cast question.
tamnt54@gmail.com wrote:
To Simplify:
class base
{
public:
virtual ~base();
};
class kid1 : public base
{
virtual ~kid1();
};
class kid2 : public base
{
virtual ~kid2();
};
You can give me a container that contains both 'kid1' and 'kid2'
objects in an ordered list and I can get them out without using
casts???
nice!
Well, the idea is that since both kid1 and kid2 both inherit from base,
then they both should have a common interface, thus eliminating the need
to know the specific type:
#include <iostream>
#include <vector>
class Base {
public:
virtual void do_something() = 0;
virtual ~Base();
};
Base::~Base() { }
class Kid1 : public Base {
public:
virtual void do_something() { std::cout << "I am a Kid1\n"; }
};
class Kid2 : public Base {
public:
virtual void do_something() { std::cout << "I am a Kid2\n"; }
};
int main()
{
using std::vector;
typedef vector<Base*> Container;
Container container;
container.push_back(new Kid1);
container.push_back(new Kid2);
typedef Container::const_iterator ConstIter;
for (ConstIter it = container.begin(); it != container.end(); ++it) {
(*it)->do_something(); // no cast needed here!
}
typedef Container::iterator Iter;
for (Iter it = container.begin(); it != container.end(); ++it) {
delete *it;
}
return 0;
}
Output:
I am a Kid1
I am a Kid2
--
Marcus Kwok
Replace 'invalid' with 'net' to reply
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]