I recently finished a bit of a program that I was hoping would work the way I expected it to, and as it turns out, it did! Here is the situation:
I have a Handler
class which is the base class:
class Handler
{
public:
Handler();
virtual ~Handler();
virtual void handle(SOCKET socket);
protected:
virtual void doWork(SOCKET socket);
private:
std::thread * handlerThread;
static void processData(SOCKET socket);
};
I have a PrintHandler
which is a subclass of Handler
:
class PrintHandler : public Handler
{
public:
PrintHandler();
~PrintHandler();
protected:
virtual void doWork(SOCKET socket);
};
Here are the definitions of doWork in the base class Handler
and the subclass PrintHandler
:
void Handler::doWork(SOCKET socket)
{
std::cerr << "If you see this, you didn't override the doWork function" << std::endl;
}
void PrintHandler::doWork(SOCKET socket)
{
std::cerr << "This is in the base class" << std::endl;
}
When I create a pointer to a PrintHandler
and cast it to a pointer to a Handler
and call the handle
method on that object via method pointer:
void Handler::handle(SOCKET socket)
{
handlerThread = new std::thread(&Handler::doWork, this, socket);
}
the doWork
executes as the subclass method that overrode the base class method. When I override a method in the manner that I did, does it replace the base class method in memory? Is there anyway to call the original base class doWork method? Does calling it with a method pointer change which method gets called?
In this thread it gives you a means to do it from the sub class. How would I call the original base class method from the base class and what does the actual structure of the object look like in memory?
I understand this is probably a lot to answer, so if you could maybe provide your knowledge on the questions in the first paragraph and suggest some reading for the questions in the second, I think that would be most appropriate.
Thank you!