I am learning C++ inheritance, so I tried this code by creating a Base class dynamically and made a downcast to its Derived class (obviously its not valid to downcast) in order
As @Mark Ransom has suggested in the comments, I looked the post When does invoking a member function on a null instance result in undefined behavior?. Then I came up with my own solution.
This behavior of invoking a non created object's method is not a matter of fact with the parent class nor child class or downcast or inheritance . I had statically told to call the child::who() by downcasting, the compiler calls child::who() without caring about the object type.
But how the
who()method is called since no object is created forchildclass?
The method which I tried to invoke doesn't have any member variable so there is no need to dereference this pointer. It just calls who(), the same behavior is true if the child class pointer points to NULL also.
child *c = NULL;
c->who();
It prints I am child even though c points to NULL. Because no need to dereference this pointer. Lets have a situation where who() method contains a member variable x as below.
class child : public parent{
private:
int x;
public:
void who(){
x = 10;
cout << "I am child " << x;
}
};
child *c = NULL;
c->who()
Now it causes Segmentation fault because in order to use x the compiler have to dereference this pointer for x as (*this).x. Since this points to NULL dereferencing will cause Segmentation fault. This is clearly an undefined behavior.