0
class A{
  int i;
  public:
  A():i(0){cout<<" A : "<<i<<endl;}
  A(int a);
    virtual int val(){ return i+1; }

};

class B :public A{
 int i;
  public:
  B():A(),i(0){cout<<" B : "<<i<<endl;}
  B(int a):A(a),i(a) {
  }

  int val(){  return i;}
};

 A::A(int a):i(a){
   cout<<" A ; "<<i<<endl;
   A* ap = new B;
   cout<<" from A "<<ap->val()<<endl; ///expect 1 but got 0;
}

int main(){
  A a(5);
}

I expected the return val of call ap->val() to be 1, since I thought virtual mechanism doesn't work in constructor, but here I got value to be 0, since ap->val() resulted in call to B::val(). Why ?

shanker861
  • 619
  • 1
  • 5
  • 9

1 Answers1

2

In this constructor

 A::A(int a):i(a){
   cout<<" A ; "<<i<<endl;
   A* ap = new B;
   cout<<" from A "<<ap->val()<<endl; ///expect 1 but got 0;
}

function call ap->val() is not applied to an object under construction.

In this statement

   A* ap = new B;

an object of type B was already created using its own constructor call and the function call is applied to the object of type B that was already created.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335