C++ Polymorphism

Could anyone tell me why is the output for the code below "Derived::foo()" and not "Base::foo()"? Revising for an exam. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Base {
 public:
 virtual void foo() { 
 cout << "Base::foo() "; }
};
class Derived : public Base {
 public:
 void foo() { 
 cout << "Derived::foo()"; }
};
void main() {
 Base *pBase = new Derived();
 pBase->foo();
 delete pBase;
}
   Base::foo()Derived::foo()
   Base::foo()    
   Derived::foo() //Correct 
Here is a runnable version of your code. (Please don't use void main()).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class Base {
public:
   virtual void foo() { cout << "Base::foo() "; }
};

class Derived : public Base {
public:
   void foo() { cout << "Derived::foo()"; }
};


int main() {
   Base *pBase = new Derived();
   pBase->foo();
   delete pBase;
}


Derived::foo()


A base class pointer can be used to point to an object of the base or any of its derived types. If the member function foo() is virtual then polymorphism allows this pointer to access the foo() of whatever class it is pointing to at runtime - here, the derived class.

If base::foo() hadn't been virtual then a base class pointer could only access the functions of the base class. (See what happens if you remove the word "virtual").


To use polymorphism like this (and get rid of compiler warnings) you should also make the base class's destructor virtual. Like so ...
virtual ~Base(){}
Last edited on
Topic archived. No new replies allowed.