Interview Question
dmelloleslie is right. The pointer is of base class, but can point to an object of derived class without giving an error message. In this case the compiler relaxes type checking. Taking the address of a derived class and treating it as the address of a base class is called "upcasting". The concept of virtual function is based on similar ideas. If the base class and the derived class both have a function defined with the same name (say foo) and you call bp->foo then the that in the base class will get invoked. However if you declare the base class foo as virtual then the function in the derived class will get invoked.
You can convert base class pointer to derived class pointer using dynamic_cast only if base class is polymorphic.
I mean
class A {
public : virtual fun() { }
};
class B : public A { };
void main()
{
B *b = new B() ;
A *a = new A();
B* nb = dynamic_cast<B*> (a); // it is ok because A is polymorphic
}
Keyur
The code you have written will compile. But not run. Since in your case a is pointing to an object of class A, after the dynamic_cast, you will have Null in nb. So it is of no use. You try to access any thing using nb and it will give Segmentation Fault. So you can case base class pointer to derived for good only when base pointer is actually pointing to a derived object or object derived from "Derived"
Below is an example where we can create base object using derived pointer
#include <map>
#include <iostream>
using namespace std;
class A
{
public:
int i;
virtual void show()
{
cout << "A::i = " << i << endl;
}
A() : i(10) {};
};
class B : public A
{
public:
int j;
void show()
{
cout << "A::j = " << j << endl;
}
B() : j(20) {};
};
int main()
{
A *a = new B();
a->show();
B *b = static_cast<B *>(new A());
b->show();
return 0;
}
Yes. A pointer of type base class can point to derived class object. But the opposite is not true. Here's how:
- dmelloleslie March 29, 2010base *bp;
derived d;
bp = &d; // base pointer points to derived object
bp->set_i(10); // access derived object using base pointer