Re: Instantiating a Derived from a Base
On May 13, 10:36 pm, Randy <gast...@sympatico.ca> wrote:
Hi,
I was learning about RTTI when I ran across this example. This line,
out of the example, confused me. It is declaring a pointer to a base
type and instantiating it with a derived class. I can say the
words ... yet I don't get it. What do I have, a base or a derived? Can
anyone push me in the right direction.
abc *abc_pointer = new xyz();
Look at it this way, all derived objects are really base objects that
have been repackaged or specialized. That means you can point to
either the whole object or the underlying base package.
A derived object does not have a base object in it. A derived object
is_a base object.
In the above code you have a derived object but the pointer holds that
base's address.
If you have the base's address you can access the derived object if
you need to.
Read about downcasting and upcasting in C++.
struct Bird { ... };
struct Eagle : public Bird { ... };
struct Pigeon : public Bird { ... };
int main()
{
Eagle eagle; // a special type of Bird
Pigeon pigeon; // another special type of Bird
Bird* p_bird = &eagle; // base ptr points to Eagle
p_bird = &pigeon; // ok, base ptr changed to point to Pigeon
Eagle* p_eagle = &eagle; // ok, no problem
p_eagle = &pigeon; // error !!!
}
/*
-------------------------------------------------------------------------------------------------
*/
#include <iostream>
class abc // base class
{
public:
virtual void hello()
{
std::cout << "in abc";
}
};Do a search for upcasting and downcasting
class xyz : public abc
{
public:
void hello()
{
std::cout << "in xyz";
}
};
int main()
{
abc *abc_pointer = new xyz();
xyz *xyz_pointer;
// to find whether abc is pointing to xyz type of object
xyz_pointer = dynamic_cast<xyz*>(abc_pointer);
if (xyz_pointer != NULL)
std::cout << "abc pointer is pointing to a xyz class object"; //
identified
else
std::cout << "abc pointer is NOT pointing to a xyz class object";
return 0;
}