When I delete the body content of Class B, errors occur on compilation.
I tried to replace "virtual void dummy() {}" with " int abc;" and the errors stills popped out on compilation.
As a beginner, I do not know why. Anyone can explain it?
Another question.
I see a pointer pointing to a base class can also be used to point to the derived classes but the members in the derived ones that are not inherited from the base class cannot be dereferenced by the pointer with an arrow operator.
Does that mean the pointer doesn't point to a complete object of the derived class type?
// dynamic_cast
#include <iostream>
#include <exception>
usingnamespace std;
class Base { virtualvoid dummy() {} };
class Derived: public Base { int a; };
int main () {
try {
Base * pba = new Derived;
Base * pbb = new Base;
Derived * pd;
pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";
pd = dynamic_cast<Derived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast.\n";
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
>To use dynamic_cast the pointer or reference must be one to a polymorphic object (ie. an object of a class type with one or more virtual functions).
Class Base is a polymorphic one, having a virtual member function.
Class Derived is derived from Base, so Derived also has that virtual member function, which means Derived is a polymorphic one, too.
So pba pointing to some Derived object can be an argument of dynamic_cast.
> I see a pointer pointing to a base class can also be used to point to the
> derived classes but the members in the derived ones that are not inherited
> from the base class cannot be dereferenced by the pointer with an arrow
> operator.
suppose that you have:
class Base{
public:
virtualvoid foo();
};
class Derived1: public Base{
public:
void bar();
};
class Derived2: public Base{
public:
void asdf();
};
int main(){
Base *p;
int n;
std::cin >> n;
if (n > 42)
p = new Derived1();
else
p = new Derived2();
p->foo(); //fine
p->bar(); //¿what do you want to happen here?
p->qwerty(); //¿and here?
}