Calling virtual functions from constructors works for me.
(Accessing data is a separate issue!)
// Re:
http://www.artima.com/cppsource/nevercall.html// "Never call virtual functions during construction / destruction"
//
#include <iostream>
using std::cout;
using std::endl;
class Base1
{
public:
Base1(){ cout << "Constructor: Base1 calling virtual Base1::vf1()..." <<endl; vf1(); }
virtual ~Base1(){ cout << "Destructor : Base1" << endl;}
virtual void vf1 () { cout << "virtual Base1::vf1 called!" << endl; }
virtual void vf2 () = 0;
};
class Derived1 : public Base1
{
public:
Derived1() { cout << "Constructor: Derived1 calling virtual Derived1::vf1()..." <<endl; vf1();
cout << "Constructor: Derived1 calling virtual Derived1::vf2()..." <<endl; vf2(); }
~Derived1(){ cout << "Destructor : Derived1" << endl;}
virtual void vf1 () {cout << "virtual Derived1::vf1 called!" << endl;}
virtual void vf2 () {cout << "virtual Derived1::vf2 called!" << endl;}
};
void main ()
{
bool use_base_class_ptr = false;
if (use_base_class_ptr)
{
Base1 *pb1 = new Derived1;
delete pb1;
/** Produces the following output: **/
// Constructor: Base1 calling virtual Base1::vf2()...
// virtual Base1::vf2 called!
// Constructor: Derived1 calling virtual Derived1::vf1()...
// virtual Derived1::vf1 called!
// Constructor: Derived1 calling virtual Derived1::vf2()...
// virtual Derived1::vf2 called!
// Destructor : Derived1
// Destructor : Base1
// Press any key to continue
}
else if (!use_base_class_ptr)
{
Derived1 d1;
/** Produces the following output: **/
// Constructor: Base1 calling virtual Base1::vf1()...
// virtual Base1::vf1 called!
// Constructor: Derived1 calling virtual Derived1::vf1()...
// virtual Derived1::vf1 called!
// Constructor: Derived1 calling virtual Derived1::vf2()...
// virtual Derived1::vf2 called!
// Destructor : Derived1
// Destructor : Base1
// Press any key to continue
}
}