Tuesday, 21 January 2014

Virtual functions in constructors and destructors

Interview question.

What does this do?

class Base
{
public:
Base()
{
log();
}
virtual ~Base()
{
log();
}

//virtual void log() = 0;//note this compiles but doesn't link
virtual void log()
{
std::cout << "Base\n";
}
};

class Derived : public Base
{
public:
Derived()
{
log();
}
~Derived()
{
log();
}
virtual void log()
{
std::cout << "Derived\n";
}
};

int main()
{
Derived d;
}

I half remembered this http://www.artima.com/cppsource/nevercall.html so wasn't sure.

No comments:

Post a Comment