0

Since I have overridden the function returnANumber in the derived class, the constructor shall return "overridden" instead of executing the branch in the parent class. But the result is different with what I expect :\

#include <iostream>
#include <string>

using namespace std;

class NewClass {
public:
    NewClass(){
        returnANumber();
    }
    virtual void returnANumber(){
        cout << "random number blah blah blah";
    }
};

class DeriveClass : public NewClass {
public:
    void returnANumber() override {
        cout << "overridden";
        }
        };

        int main(){
            NewClass NewClass;
            DeriveClass DeriveClassInst;
            DeriveClassInst.returnANumber();
        }

Result: "random" "random" "overridden" The member function seems to be overridden at last, but it didn't work with the constructor. Expected output: "random" "overridden" "overridden"

Merk
  • 15
  • 3
  • You probably want to post the rest (a small main indicating with calls where the output confuses you). Show the expected and actual output. – kabanus Jan 04 '17 at 11:46
  • @StoryTeller answer there is terrible in my opinion, it may be worth letting people answer here with a proper answer to what's happening. – kabanus Jan 04 '17 at 11:53
  • @kabanus But that's not possible, since undefined behaviour cannot be explained in a general case. Each compiler can and will do whatever it wants, based on the resulting logic tree from the implmentation. – Mio Bambino Jan 04 '17 at 11:55
  • The reason is that C++ objects are constructed from the inside out. Base-classes are constructed before derived classes. So, before a Derived class is made, a base class must be made. When Base's constructor is called, it's not in derived yet and so the virtual function table still has the entry for base's copy of function(). – evk1206 Jan 04 '17 at 11:55
  • @kabanus - There is a more detailed, better answer to the same question. It just wasn't accepted. – StoryTeller - Unslander Monica Jan 04 '17 at 11:56
  • @StoryTeller I stand corrected. OP scroll down a bit there. – kabanus Jan 04 '17 at 11:56
  • @MioBambino - There's no undefined behavior here. Dynamic function dispatch isn't preformed inside the constructor. – StoryTeller - Unslander Monica Jan 04 '17 at 11:57
  • Thx guys, I know what to do now – Merk Jan 04 '17 at 12:03

0 Answers0