Here for example since Node is a object with size 8 bytes(2 int). So suppose starting address of the allocated block be
0x1000 so after changing the pointer address to 0x1001. I am still pointing to the block.
So, I understand being not able to access the data members but then why am I correctly able to call the member functions? Is it because member functions are common to all the objects of a class and are independent to where the object pointer is pointing to??
member functions are common to all the functions, otherwise there would be a lot of wasted memory, and that's why sizeof() only returns the size of the data members
So all member functions are are functions that have an implicit parameter that is a pointer to the instance's data members. If the member function is non-virtual, the call to the member function can be made successfully by the compiler even if the pointer is completely bogus. What causes the crash is when the member function tries to access the instance data through that pointer.
To illustrate, try the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
class A {
public:
void foo() { cout << "foo called" << endl; }
void bar() { x = 4; }
private:
int x;
};
int main() {
A* a = 0;
a->foo();
cout << "Calling bar..." << endl;
a->bar();
}
and then as a second test make foo virtual and note that the program crashes even before "foo called" is printed.