Smart pointer

These code compile correctly, but instead of A2 *p=dynamic_cast<A2*>(&(*vect[i])); I'd like to have this A2 *p=dynamic_cast<A2*>(vect[i]);
...How can I get this?

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
 #include <iostream>
#include <vector>
using namespace std;
class A{
  public:
  virtual ~A(){}
};
class A2: public A{
};
class B{
class smart{
public:
  A* pointer;
  A* operator->() const {return pointer;}
  A& operator*() const {return *pointer;}
};
  public:
vector<smart> vect;
void foo(){
 for(int i=0;i<vect.size();i++){
 A2 *p=dynamic_cast<A2*>(&(*vect[i]));
 }
}
};
int main(){
}
!indent
1
2
3
4
5
6
class smart{
public:
   operator A*(){
      return pointer;
   }
};
please someone explain. By A2 *p=dynamic_cast<A2*>(&(*vect[i])); we are dynamic casting base class pointer to a derived class pointer. is it allowed?
nothing, it doesn' t work either with the redefinition of the operator A*() ...it keep on saying that "target is not a pointer or a reference...
vect[i] has the type B::smart. It's not a pointer or a reference. dynamic cast cannot not be applied to an expression of that type. Operator overloads don't come into play.

Look at standard shared pointers: they have a .get() function that returns the raw pointer, which can be dynamic_cast, and shared_ptr even has a special function, std::dynamic_pointer_cast which wraps those steps.
Topic archived. No new replies allowed.