0

They both compile.

I do not understand why the method works even though the pointer is set to NULL. ...and then, the virtual one does not. (it crashes at run-time)

THE CODE:

#include "stdafx.h"

class Person {
public:
    void PrintHello() { 
    printf("Hello \n\n"); 
    }

    ~Person() {}
};

class Student {
public:
    virtual void PrintHello() {
    printf("hello");
    }

    virtual ~Student() {
    }
};


int main() {

Person* p = NULL;
    p->PrintHello();

    Student* s = NULL;
    s->PrintHello();

    return 0;
}

... thanks a lot.

user2700212
  • 21
  • 1
  • 3
  • Because the function code is there even if the object is not. Without the object the vtable pointer will be undefined so virtual functions will not work. Such code exhibits undefined behavior. – Galik Feb 25 '17 at 10:25
  • OK I see now that there is a duplicate. I did not find it in the search, sorry. and thanks also to Galik. – user2700212 Feb 25 '17 at 10:28
  • [None of this works for me](http://coliru.stacked-crooked.com/a/43fe8bb6fa866f90) – Code-Apprentice Feb 25 '17 at 10:30

0 Answers0