virtual functions overriding

Mar 8, 2020 at 5:46pm
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;
}
Mar 8, 2020 at 6:02pm
Well your first bptr is uninitialised.
Perhaps you should print dptr on line 24 to begin with.
Mar 8, 2020 at 6:06pm
First:
1
2
base *bptr;
cout << "bptr:" << bptr << endl; // warning: bptr is used uninitialized 


Second, your 'derived' does not override 'func()'. func != fun
Mar 9, 2020 at 12:31am
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;
}
Mar 9, 2020 at 3:19am
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 Mar 9, 2020 at 3:21am
Topic archived. No new replies allowed.