Ioannis Vranos wrote:
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:01******** ***********@new sread1.news.pas .earthlink.net. ..
"Upcasting" is never necessary, as far as I can tell. dynamic_cast is
used for checked downcasting (e.g., if I cast from Shape to Triangle,
ensures that the Shape really was a Triangle).
Yes my silly mistake. Downcasting and crosscasting is dynamic_cast about.
Upcasting needs no casting.
OK, which way is up? Actually, I didn't even think about that issue. But now
that I think about it. A dynamic_cast would be the thing to use. Upcasting
actually means to cast from a derived to a base class, and _does_, I'm
pretty sure, require a static_cast.
This is a little exercise I made up to try to get a handle on all this.
It's a very tricky topic.
/* Hava Fun */
#include <iostream>
#include <string>
using std::ostream;
using std::string;
using std::cout;
class A{
public:
A(const string& name = "A"):m_name(nam e)
{}
virtual ostream& toString (ostream& out) const;
friend ostream& operator<<(ostr eam& out, const A& a);
protected:
string m_name;
};
ostream& A::toString (ostream& out) const{
return out << this->m_name;
}
ostream& operator<<(ostr eam& out, const A& a)
{
return a.toString(out) ;
}
class B:public A
{
public:
B(const string& name = "B"):A(name )
{}
ostream& toString (ostream& out) const;
};
ostream& B::toString (ostream& out) const{
A::toString(out );
return out << this->m_name;
}
ostream& operator<<(ostr eam& out, const B& b)
{
return b.toString(out) ;
}
int main()
{
A a;
B b;
A* aa_ptr = &a;
A* ab_ptr = &b;
B* bb_ptr = &b;
cout << "A* aa_ptr = &a: " << *aa_ptr << std::endl;
cout << "A* ab_ptr = &b: " << *ab_ptr << std::endl;
cout << "B* bb_ptr = &b: " << *bb_ptr << std::endl;
ab_ptr = static_cast<A*> (&b);
cout<<"ab_ptr = static_cast<A*> (&b): " << *ab_ptr << std::endl;
ab_ptr = dynamic_cast<A* >(&b);
cout << "ab_ptr = dynamic_cast<A* >(&b): " << *ab_ptr << std::endl;
cout << "cout <<(A)*ab_ptr << std::endl;: " <<(A)*ab_ptr << std::endl;
cout << "cout << static_cast<A>( *ab_ptr) << std::endl;: ";
cout <<static_cast<A >(*ab_ptr) << std::endl;
cout << "cout << *dynamic_cast<A *>(ab_ptr) << std::endl;: ";
cout << *dynamic_cast<A *>(ab_ptr) << std::endl;
}
--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop:
http://www.kdevelop.org SuSE:
http://www.suse.com
Mozilla:
http://www.mozilla.org