Please take a look at the code below. I wonder what happens when the virtual keyword is not in the base class but in the derived class? will the run() function from class A override the run() function in class B?
Also what I don't understand is the line: A *a = new C();;
Does that make a of Class A or C? and why does it use two cast operators, static and dynamic? the cast operator takes the argument (a and b) as of which class type?
Sorry for a bit more questions, this virtual and casting things are so confusing.
Thanks.
#include <iostream>
usingnamespace std;
class A {
public:
A() : val(0) {}
int val;
void run() { cout << val; }
};
class B : public A {
public:
virtualvoid run() { cout << val + 2; }
};
class C : public B {
};
void Do(A *a) {
B *b;
C *c;
if(b = static_cast<B *>(a))
b->run();
if(c = dynamic_cast<C *>(b))
c->run();
a->run();
}
int main() {
A *a = new C();;
Do(a);
return 0;
}