Hi all,
I'm studying C++ and starting to get my way around it. There is one thing that I'm not sure how to understand. That is that b doensn't become an object of Derived. Should I understand this as a rule (don't like that) or is there a better description?
class Base {
public:
int base;
void get(){
cout << "Base:"<< base;
}
};
class Derived : public Base {
public:
int derived;
void get(){
cout <<"\nDerived:"<< derived;
}
};
int main(){
Base *b;
b = new Base();
b->base = 25;
b->get();
b = new Derived();
b->get();
return 0;
}
Line 25: You create a new object of type Derived and assign it to a pointer of type Base. Since Base has no virtual functions, you are effectively downcasting from Derived to Base. i.e. Base is not polymorphic.
If you want line 26 to display the value of derived (line 12), you need to add the virtual keyword at line 4.
BTW, line 12 is uninitialized. Therefore, displaying derived will result in undefined behavior.