Interactive Brokers Interview Question
what if class contain virtual function . then "this" pointer points to virtual table .
is not this also sets virtual ptr to 0?? plz correct me
I can confirm your point. See:
#include <iostream>
#include <cstring>
using namespace std;
class Foo {
public:
virtual void hello() const {
cout << "Hello world" << endl;
}
};
int main(void){
Foo f;
cout << sizeof(f) << endl;
unsigned long* ptr = (unsigned long*)&f;
cout << *ptr << endl;
memset(&f, 0, sizeof(f));
cout << *ptr << endl;
return 0;
}
vptr
gets created in both kind of objects (statically created or dynamically created)
class base{
int i;
virtual void show() {..}
};
1. Statically created:
base b;
2. Dynamically created:
base *b = new base();
Point is when you access any virtual function through these objects then vptr is used or not.
case 1st :- Vptr is not used. So even if vptr is NULL, still virtual function can be called, because there is no polymorphism.
case 2nd:- Vptr is used. If Vptr is NULL , then calling to virtual function will give null pointer exception.
I think its a clean way to start with. Since we Zero out the entire object space, we can make sure that un-initialized members of the class are not pointing to some junk data.
- Anonymous September 11, 2010