wrote:
> Dear All,
> According to OOPs , a base class pointer can to point to derived class
> object....call this as fact1
> But somehow I am not comfortable while understanding this concept.
> The explanaition to the fact1 is given as since the derived object
> always consists of the base part , the base class pointer will always
> point to the base part in the derived object unless otherwise the
> function in the base class are declared as virtual and are overrided in
> the derived class.
> My confusion is, since the derived class always consists of the base
> class part in it,it should be more logical to think that the pointer to
> the derived class can store the address of the base class object as it
> will be always carrying the base class related services and data with
> it.
> This confusion gives me lot of headech while studying the COM and other
> advanced concept . will someone please give me any good explaination or
> justification of where my thinking process is going wrong(straying??)?.
> I will be very grateful to him..
class A
{
public:
void f();
};
class B : public A
{
public:
void g();
};
Now, objects of type A can call f() and objects of type B can call
either f() or g().
int main()
{
A a;
B b;
a.f(); // ok
a.g(); // error
b.f(); // ok
b.g(); //ok
A *pa = &b; // ok
B *pb = &a; // that's illegal, but what if
pa->f(); // ok
pa->g(); // error
pb->f(); // ok
pb->g(); // ok !!! pb actually points to an A and As don't
// have g() !
}
By having pb point to a A, the compiler accepted the call to g(), even
if the object we are pointing at (actually a A) does not contain such
member function. That's because the function calls are checked on the
static type of the object (which is A*), not on the dynamic type (which
is B*).
You can implicitly cast pointers to a base class, because the compiler
is 100% sure the object pointed to *is a* base class (it is perhaps more
than that, such as a B or a C, but it is at least a base class). You
can not implicitly cast pointers to a derived class, because the
compiler cannot check if the object *is a* derived class.
void f(B *a)
{
// does a really point to a B?
}
void g1()
{
A a;
f(&a); // no it does not, so that must be illegal
}
void g2()
{
B b;
f(&b); // yes it does, so that's legal
}
There are (unfortunately) some circumstances where *you* know for sure
an A* is a B*, so you are able to do the cast explicitly. Using
dynamic_cast over static_cast can make things a bit more safer.
Jonathan