Calling virtual functions inside constructors

Suppose I have two C++ classes:

class A
{
public:
  A() { fn(); }

  virtual void fn() { _n = 1; }
  int getn() { return _n; }

protected:
  int _n;
};

class B : public A
{
public:
  B() : A() {}

  virtual void fn() { _n = 2; }
};

If I write the following code:

int main()
{
  B b;
  int n = b.getn();
}

One might expect that n is set to 2.

It turns out that n is set to 1. Why?

15 Answers
15

Leave a Comment