virtual functions overriding

Hi,
Below is my code, i was expecting an error from program because when i print the base pointer before and after assigning derived pointer it is different.

despite holding derived pointer, which does not have the invoking function
the program works , i mean prints "base", how?

should not it print func is not available in derived class?

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
30
#include <iostream>

using namespace std;

class base{
    
    public:
    void virtual func(){
        cout<<"base"<<endl;
    }
};

class derived: public base{
    public:
    void fun(){
        cout<<"derived"<<endl;
    }
};

int main() {
    
    base *bptr;
    derived *dptr = new derived;
    cout<<"bptr:"<<bptr<<endl;
    bptr = dptr;
    cout<<"bptr:"<<bptr<<endl;
    bptr->func();
    
    return 0;
}
Well your first bptr is uninitialised.
Perhaps you should print dptr on line 24 to begin with.
First:
1
2
base *bptr;
cout << "bptr:" << bptr << endl; // warning: bptr is used uninitialized 


Second, your 'derived' does not override 'func()'. func != fun
My question is bptr is pointing to dptr and when we call bptr->func() ( func is actually not available in class derived ) why is it not throwing an error, how come bptr is able to call class base , though it is having class derived address.

code:

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
30
31
32
33
34

#include <iostream>

using namespace std;

class base{
    
    public:
    void virtual func(){
        cout<<"base"<<endl;
    }
};

class derived: public base{
    public:
    void fun(){
        cout<<"derived"<<endl;
    }
};

int main() {
    
    base *bptr = new base;
    cout<<"first bptr: " <<bptr <<"\n";
    bptr->func();
    derived *dptr = new derived;
    cout<<"bptr: "<<bptr<<"  dptr"<< dptr<<endl;
    bptr = dptr;
    cout<<"bptr:"<<bptr<<endl;
    bptr->func();
    
    return 0;
}
The Liskov Substitutability Principle says that an instance of a derived class must be usable anywhere a base class is acceptable. This is one of the basic ideas behind object-oriented programming, part of the so-called SOLID principles.
https://en.wikipedia.org/wiki/SOLID

Public inheritance models the is-a relationship:
A derived class is-a (specialization of its) base class.

As such, the derived class inherits all the public and protected data and behavior from the base class.
Last edited on
Topic archived. No new replies allowed.