
Hello Please tell me how can base class pointer be assigned to derived class pointer? are they both same? if they then how? Please reply must. regrads Hammad

Greetings -- Hammad <mh00219@surrey.ac.uk> writes:
Please tell me how can base class pointer be assigned to derived class pointer? are they both same? if they then how?
I think that the short answer to your question is to include #include <boost/pointer_cast.hpp> then, if your classes are polymorphic (i.e., they have 'virtual' methods), use 'boost::dynamic_pointer_cast'; otherwise, use 'boost::static_pointer_cast'. The dynamic casts require a vtable, but they have the advantage of checking that a given cast is correct (that the base pointer really is to that derived class, or some class further down that tree of the hierarchy). A static cast simply takes your word for it. A longer example: #include <iostream> #include <boost/pointer_cast.hpp> #include <boost/shared_ptr.hpp> class base { public: base() {} }; class derived : public base { public: derived() : base() {} special() { std::cout << "special" << std::endl; } }; int main( int argc, char * argv [] ) { // this is fine, since a "base *" can hold a "derived *" boost::shared_ptr< base > bsp( new derived() ); // error! the compiler only sees the static type, and 'base' has // no method named 'special'. bsp->special(); // error! // so we need to make a shared pointer with "derived" as the // pointed-at type: boost::shared_ptr< derived > dsp = boost::static_pointer_cast< derived >( bsp ); // now the static type has the 'special' method: dsp->special(); return 0; }
participants (2)
-
Anthony Foiani
-
mh00219@surrey.ac.uk