0

In the code below, c_p must be storing the address of derived class object. Please explain why comment 1. prints "base" and, 2. prints "derived".

class C{
private:
    int a;
    C *c_p;
public:
    virtual void print(){
        cout << "base";
    };
    C(int x): a(x), c_p(this){
        //1.
        c_p->print();
    }
    void print_data(){
        c_p->print();
    }
};

class S : public C{
private:
    int b;
public: 
    void print(){
        cout << "derived";
    }
    S(int x ,int y): C(x), b(y){}
};

int main(){
    S s_o(5, 3);
    //2. 
    s_o.print_data();
    cout << "Hello, world\n";
    return 0;
}
  • Does https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors explain the situation for you? – TheUndeadFish Feb 05 '20 at 03:13
  • Calling a virtual method before the constructor completes (or after the destructor has started) is undefined behavior. Note: A class with a virtual method should probably have a virtual destructor. – Martin York Feb 05 '20 at 03:16
  • 1
    @MartinYork It's not undefined behaviour. It calls the most derived override visible from the current class scope. This is specified behaviour. – user207421 Feb 05 '20 at 03:23
  • @TheUndeadFish : thanks for the comment. Now it makes sense why the output was like that. – user3809584 Feb 05 '20 at 04:22
  • @user207421 Seems you are correct: 10.9.4 Construction and destruction [class.cdtor] Paragraph 4 (n800). Any idea when this behavior was changed (or have I always been wrong)? – Martin York Feb 05 '20 at 23:39

0 Answers0