I was asked this question in an interview and I was unsure of the behaviour in the following case :
class A
{
virtual fun1(){...}
virtual fun2(){...}
};
class B : public A
{
virtual fun1(){...}
virtual fun2(){...}
};
Now if,
A* AObj = new A;
B* BObj = (B*) AObj;
Does BObj
have access to B's methods because of the virtual keyword or does it not because it's pointing to an object of AObj
?
Can someone help me with how exactly downcasting affects access also ?
Assigning an address of a base-class object to a derived-class pointer is undefined behavior. So anything can happen: calling BObj
's functions can invoke B
's functions, can invoke A
's functions, can crash the program, or even format your hard drive. This will all depend on compiler and its optimization options.