Vector, polymorphism, new and returns

I'm getting a little confused to what to do here.
There's a lot going on my code so I'll try to simplify it with just my confusing/problem.

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
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()
  {
     ...
     return new 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
return new 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.
Last edited on
Hum, how? I'm not seeing how it would work.
DoWork() needs to return a B that is a copy of a B that exists in that vector.
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.

See http://www.cplusplus.com/reference/typeinfo/bad_cast/

EDIT:
Sorry, if you are using pointers I don't think you need to check for std::bad_cast, just check to see if a nullptr has been returned instead.
Last edited on
I tried dynamic_cast but got curious on his alternative.

Using dynamic_cast I ended up with something like this:

return new B( *(dynamic_cast<B *>(infos.doSomething('b')) );

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.
Last edited on
Oh, if you want to get a copy, you should use the Clone Pattern.
I don't think I'm allowed to use that. This is part of a programming class' project and I don't recall the teacher ever talking about that.

Casts however he did talk about and dynamic_cast is doing the trick for now.

Thanks!!
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.
Topic archived. No new replies allowed.