<p>In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.</p>

<p>I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:</p>

<p>As long as the derived constructor has not been executed the object is <strong>not</strong> yet a <em>derived</em> instance.</p>

<p>So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:</p>

<pre><code>class base {
public:
    base()
    {
        std::cout &lt;&lt; "foo is " &lt;&lt; foo() &lt;&lt; std::endl;
    }
    virtual int foo() { return 42; }
};

class derived : public base {
    int* ptr_;
public:
    derived(int i) : ptr_(new int(i*i)) { }
    // The following cannot be called before derived::derived due to how C++ behaves, 
    // if it was possible... Kaboom!
    virtual int foo()   { return *ptr_; } 
};
</code></pre>

<p>It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for <em>the principle of least surprise</em>? </p>

<p>Which do you think is the correct choice?</p>

[{'answer_id': 36837, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 3, 'selected': False, 'text': "<p>Both ways can lead to unexpected results.  Your best bet is to not call a virtual function in your constructor at all. </p>\n\n<p>The C++ way I think makes more sense, but leads to expectation problems when someone reviews your code.  If you are aware of this situation, you should purposely not put your code in this situation for later debugging's sake.</p>\n"}, {'answer_id': 36844, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 1, 'selected': False, 'text': "<p>I think C++ offers the best semantics in terms of having the 'most correct' behavior ... however it is more work for the compiler and the code is definitiely non-intuitive to someone reading it later.</p>\n\n<p>With the .NET approach the function must be very limited not to rely on any derived object state.</p>\n"}, {'answer_id': 37322, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>Virtual functions in constructors, why do languages differ?</p>\n</blockquote>\n\n<p>Because there's no one good behaviour.  I find the C++ behaviour makes more sense (since base class c-tors are called first, it stands to reason that they should call base class virtual functions--after all, the derived class c-tor hasn't run yet, so it may not have set up the right preconditions for the derived class virtual function).</p>\n\n<p>But sometimes, where I want to use the virtual functions to initialize state (so it doesn't matter that they're being called with the state uninitialized) the C#/Java behaviour is nicer.</p>\n"}, {'answer_id': 75026, 'author': 'Lars Truijens', 'author_id': 1242, 'author_profile': 'https://Stackoverflow.com/users/1242', 'pm_score': 0, 'selected': False, 'text': '<p>Delphi makes good use of virtual constructors in the VCL GUI framework: </p>\n\n<pre><code>type\n  TComponent = class\n  public\n    constructor Create(AOwner: TComponent); virtual; // virtual constructor\n  end;\n\n  TMyEdit = class(TComponent)\n  public\n    constructor Create(AOwner: TComponent); override; // override virtual constructor\n  end;\n\n  TMyButton = class(TComponent)\n  public\n    constructor Create(AOwner: TComponent); override; // override virtual constructor\n  end;\n\n  TComponentClass = class of TComponent;\n\nfunction CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;\nbegin\n  Result := ComponentClass.Create(AOwner);\nend;\n\nvar\n  MyEdit: TMyEdit;\n  MyButton: TMyButton;\nbegin\n  MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;\n  MyButton := CreateAComponent(TMyButton, Form) as TMyButton;\nend;\n</code></pre>\n'}, {'answer_id': 75654, 'author': 'Daniel James', 'author_id': 2434, 'author_profile': 'https://Stackoverflow.com/users/2434', 'pm_score': 5, 'selected': True, 'text': "<p>There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object.</p>\n\n<p>In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body.</p>\n\n<p>The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed.</p>\n"}, {'answer_id': 77445, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I have found the C++ behavior very annoying. You cannot write virtual functions to, for instance, return the desired size of the object, and have the default constructor initialize each item. For instance it would be nice to do:</p>\n\n<p><code>BaseClass() {\n   for (int i=0; i&lt;virtualSize(); i++)\n     initialize_stuff_for_index(i);\n}</code></p>\n\n<p>Then again the advantage of C++ behavior is that it discourages constuctors like the above from being written.</p>\n\n<p>I don't think the problem of calling methods that assume the constructor has been finished is a good excuse for C++. If this really was a problem then the constructor would not be allowed to call <em>any</em> methods, since the same problem can apply to methods for the base class.</p>\n\n<p>Another point against C++ is that the behavior is much less efficient. Although the constructor knows directly what it calls, the vtab pointer has to be changed for every single class from base to final, because the constructor might call other methods that will call virtual functions. From my experience this wastes far more time than is saved by making virtual functions calls in the constructor more efficient.</p>\n\n<p>Far more annoying is that this is also true of destructors. If you write a virtual cleanup() function, and the base class destructor does cleanup(), it certainly does not do what you expect.</p>\n\n<p>This and the fact that C++ calls destructors on static objects on exit have really pissed me off for a long time.</p>\n"}]
['https://Stackoverflow.com/questions/36832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848/']