0

Possible Duplicate:
Calling virtual method in base class constructor
Calling virtual functions inside constructors

How can I call a protected virtual method from a constructor in C++?

class Foo
{
   Foo(){
       printStuff();  // have also tried this->printStuff()
   }
  protected:
   virtual void printStuff() {}
}

class ExtendedFoo : public Foo {
  protected:
   virtual void printStuff() { cout << "Stuff" << endl;}
}

...

ExtendedFoo exFoo; // should print "Stuff"
Community
  • 1
  • 1
chillitom
  • 24,888
  • 17
  • 83
  • 118

4 Answers4

3

There's no problem in calling a protected function from the constructor - just do it. However, what you seem to be wanting is to call into a concrete derived class' implementation of it, e.g., ExtendedFoo's, since it's virtual - right? That's a no-go, since inside the Foo constructor, the object being created is still of type Foo, not ExtendedFoo, so no virtual dispatch can take place. If the protected function isn't pure virtual, the Foo implementation is called, i.e., the constructor will call the class' own implementation.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
1

Consider that when your base constructor is called, your actual constructor still does not, so you object is not completely formed.

If your object isn't yet formed, you can't expect it to act correctly.

Please read this:

j4x
  • 3,595
  • 3
  • 33
  • 64
0

You can, but you will get Foo's implementation because ExtendedFoo's not been constructed. This is defined.

Similar problem: C++ design pattern: multiple ways to load file

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
0

Answer deprecated after question change:

If it is protected in ExtendedFoo, you can not call it from outside of ExtendedFoo. The line...

exFoo.printStuff();

violated the function's protection level.

http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr129.htm

Foggzie
  • 9,691
  • 1
  • 31
  • 48