Possible Duplicate:
C++ virtual function from constructor
Calling virtual functions inside constructors
This question was asked in interview .
I guess I had answered the 1st part correctly but not sure about the 2nd part. In fact I have no clue about 2nd part.
- What output does the following code generate? Why?
- What output does it generate if you make A::Foo() a pure virtual function?
When I tried running same question on my compiler with virtual void foo() = 0; it throws
error “undefined reference to `A::Foo()'”
#include <iostream>
using namespace std;
class A
{
public:
A()
{
this->Foo();
}
virtual void Foo()
{
cout << "A::Foo()" << endl;
}
};
class B : public A
{
public:
B()
{
this->Foo();
}
virtual void Foo()
{
cout << "B::Foo()" << endl;
}
};
int main(int, char**)
{
B objectB;
return 0;
}
When you instantiate a
Bobject, the following happens:B‘s constructor is called.First thing,
B‘s constructor calls the base constructorA().Inside
A‘s constructor, the function call is dispatched toA::foo(), sincethishas static and dynamic typeA*(nothing else makes sense if you think about it); now theAsubobject is complete.Now
B‘s constructor body runs. Here the function call is dispatched toB::foo(). Now the entireBobject is complete.If
A::foo()is pure-virtual, step (3) causes undefined behaviour; cf. 10.6/4 in the standard.(In your case possibly manifesting as a linker error, since the compiler optimizes to resolve the call statically, and the symbol
A::foois not found.)