class inheritance

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  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.
Thank you.

It makes Abstract classes much more clear to me.

I do now understand why it is that b is NOT an object of Derived but stays a pointer to Base.

I do now also understand that when the function in Base is virtual the functions with the same name in the Derived is also virtual.

It's awesome.

BTW: Yes I forgot to initialize the variable derived.
Topic archived. No new replies allowed.