class A
{
char letter;
A() { letter = 'a';}
...
};
class B : public A
{
B() { setLetter('b'); }
...
};
class C : public A
{
C() { setLetter('c'); }
...
};
class Infos
{
...
vector<A *> letters;
Infos(){
letters.push_back(new A());
letters.push_back(new B());
letters.push_back(new C());
}
...
...
A * doSomething(char x)
{
vector<A *>::iterator it;
for (it = letters.begin(); it != letters.end(); ++it)
if ((*it)->getLetter() == x)
return (*it);
}
};
class Work
{
Infos infos;
...
...
...
B * doWork()
{
...
returnnew B(infos.doSomething('b'));
}
};
This is basically what I have. My problem is the return in doWork(). It won't allow it to be like that even if doSomething('b') is actually returning a B (or at least I think it is).
I tried returnnew B((B *)infos.doSomething('b'));
but it didn't work either.
Any lights on this?
Look up dynamic_cast - just keep in mind the fact that you even need to do this at all means you have a design flaw. Why not have a doWork function in A? Then you need not care whether it's an A, B, or C.
As @L B said, why not dynamic_cast: You can use it to cast a base into a derived, with run-time type checking. Just make sure to put it into a try-catch block to catch std::bad_casts.
I don't know if this is correct or not. At least the compiler doesn't give me any errors. I can't test for now because I have to finish other parts of the code.
The Clone Pattern isn't exactly a feature of C++, it's just something you can do within the bounds of the language. I would be extremely surprised if your teacher wanted you not to do something similar to it.