Issue with dynamic casting

Hi,
I decided to create a function that would do a dynamic cast to a pointer and throw and exception if the cast couldn't be done. Something like this:

1
2
3
4
5
6
7
8
void CastToParticle( Particle* P, Base* B) throw MyException {
  try {
    P = dynamic_cast<Particle*>( B );
  } catch ( const std::bad_cast& e ) {
    delete P;
    throw MyException("Whatever");
  }
}


But, when doing this:
1
2
3
Particle* restrict P(NULL);
CastToParticle( P, base_point );
std::cout << P->Index() << "\n"; 

it segfaults. However, if the code is:

1
2
3
4
5
6
7
8
Particle* restrict P(NULL);
try {
  P = dynamic_cast<Particle*>( base_point );
} catch ( const std::bad_cast& e ) {
  delete P;
  throw MyException("Whatever");
}
std::cout << P->Index() << "\n"; 


it goes allright.

Any idea?
Thanks in advance.
The first version doesn't modify the P pointer in the caller, it modifies the P pointer in CastToParticle(). Pass either a Particle ** or a Particle *&.
Ok!

I changed the function header to CastToParticle(Particle* restrict &P, Base* B) and it went all fine.

However, I still don't understand what you said in your post, helios:

doesn't modify the P pointer in the caller, it modifies the P pointer in CastToParticle()


Shouldn't be allright since P is a pointer?

Thanks!
For my next example, I'll simplify your code:
1
2
3
4
5
6
void f(T *p){
    p=foo;
};
//...
T *p;
f(p);

A pointer is an integer, correct? Its assignment semantics are identical to an integer's, and this is sufficient for our example. If I change the type of p, my point becomes clear:
1
2
3
4
5
6
void f(int p){
    p=foo;
};
//...
int p;
f(p);
Ok! Thanks helios!
Topic archived. No new replies allowed.