C++ Polymorphism

Why is the output 'B' instead of 'BD'. Do not get it..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Given the following code:
class B {
public:
  virtual void foo();
};

void B::foo() { cout << "B"; }
  
class D : public B {
public:
  virtual void foo() { 
     B::foo(); cout << "D"; 
  }
};
 
int main() {
  B b;
  B *pB = &b;
  pB->foo();
  return 0;
}
If this code is compilable, what is the output? Type NC if it is not compilable. 
B
The base-class pointer only points to an object of type B, so at runtime B's foo() is all it calls.

Try changing the first line of main() to
D b;
Then, at runtime, the base-class pointer will be pointing at D's foo() and give you what you want.
pB points to an object of type B so that is why pB->foo() will call B::foo() which outputs "B".

If you change so that pB points to an object of type D you would instead get "BD" as output.

1
2
3
D d;
B *pB = &d;
pB->foo(); // prints "BD" 
Topic archived. No new replies allowed.