Run time polymorphism not working

In my opinion the code should run,why is it not running?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
class Base
{
public:
	virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base
{
public:
	void show(int i) { cout<<"In Derived \n"; }
};

int main(void)
{
    Derived d;
	Base *bp ;
	bp= &d;
	bp->show(5); // RUN-TIME POLYMORPHISM

	return 0;
}
Last edited on
prog.cpp: In function ‘int main()’:
prog.cpp:20:12: error: no matching function for call to ‘Base::show(int)’
  bp->show(5); // RUN-TIME POLYMORPHISM
            ^


show(int) and show(<no args>) are two different function signatures. You're not overriding any base-class behavior.

Change them both to be the same signature.

Also, use override as an optional safety check to make sure you're actually overriding something.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
class Base
{
  public:
    virtual void show(int i) { cout<<" In Base \n"; }
    virtual ~Base() {}
};

class Derived: public Base
{
  public:
    void show(int i) override { cout<<"In Derived \n"; }
};

int main(void)
{
    Derived d;
    Base *bp ;
    bp= &d;
    bp->show(5); // RUN-TIME POLYMORPHISM

    return 0;
}


Also, you should give polymorphic base classes virtual destructors.
https://stackoverflow.com/a/461237
Last edited on
Topic archived. No new replies allowed.