C++: calling methods from constructors

One and a half months ago I posted a question on Java. Now it’s time for its counterpart in C++:

#include <tchar.h>
#include <iostream>

using namespace std;

class Parent
{
public:
    Parent()
    {
        test();
    }

    virtual void test()
    {
        cout << "Hello from parent\n";
    }
};

class Child : public Parent
{
private:
    char *name;

public:
    Child()
    {
        name = "Hi";
    }

    virtual void test()
    {
        cout << "Hello from child " << name <<  "\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
      Child();
      return 0;
}

What does it print?
The answer is obvious if you compile and run it? Can you answer it without running?

Advertisements

One Response to “C++: calling methods from constructors”

  1. Rio Wing Says:

    It’s more likely “Hello from parent\n”, but I don’t think the c++ standard clearly states this. It depends on the implementation, in another word, when the vtable pointer gets updated. VC and Borland C++ are very likey show different result.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: