0

Possible Duplicate:
Calling virtual function of derived class from base class constructor?

I have the following files (forgive typos, I rewriting the code fast from memory)

BaseReader(){
    openFile();
}

void BaseReader::openFile(){
    //logic to open file
}

Open file is declared as virtual public method (it was protected, but I swtiched it to public while trying to figure out what is wrong) in the .h. SortReader is defined as:

class SortReader: public BaseReader{
    public:
            SortReader();
            void openFile();
    };

with the following code:

SortReader::SortReader(): BaseReader(){}

SortReader::openFile(){
    sortFile();
    BaseReader::openFile();
}

When I Try constructing a SortReader object the sortFile method is never called. I can walk through it in a debugger and watch the SortReader call the BaseReader constructor The BaseReader constructor calls openFile which calls the BaseReader version of openFile. I want it to call SortReader's implimentation of open file. What do I need to do to have that happen?

Community
  • 1
  • 1
dsollen
  • 6,046
  • 6
  • 43
  • 84
  • 2
    Obviously the issue is that `openFile()` isn't declared as virtual... – Richard J. Ross III Jul 03 '12 at 17:20
  • @RichardJ.RossIII: According to the question it is, although without seeing the declaration we can't be completely sure. But whether it is or not, you can't call the derived class version from the base class constructor. – Mike Seymour Jul 03 '12 at 17:41

1 Answers1

2

You can't. Until the constructor finishes, the object is not yet fully constructed. In general, calling virtual methods from a constructor is a bad idea.

You can delegate the logic to a separate non-virtual method:

SortReader::openFile(){
    sortFileInternal();     //not virtual
                            //defined in SortReader
    BaseReader::openFile();
}

SortReader::sortFile()      //the virtual method
{
    sortFileInternal();
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625