1

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 ?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Vishnu Nair
  • 137
  • 1
  • 5
  • You can just try it in ideone.com or anywhere: http://ideone.com/B7P6DN (this gives me runtime error) – Melkon Aug 03 '15 at 08:15

3 Answers3

5

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.

Community
  • 1
  • 1
Petr
  • 9,812
  • 1
  • 28
  • 52
2

In such cases (polymorphism) the type of pointer (BObj, here its type is not B) is the type of object it is pointing to (A). so BObj is object of Base class and is incapable of doing extra work (functions) defined in derieved class (B).

Ali Kazmi
  • 1,460
  • 9
  • 22
2

First of all, doing this

A* AObj = new AObj();

B* BObj = AObj;

is not safe at all, because it assigns the address of a base-class object (Parent) to a derived class (Child) pointer. So, the code would expect the base-class object to have derived class properties.

However you can do this:

    A* AObj = new AObj();

    B* BObj = dynamic_cast<B*>AObj;

This will check if Aobj can be assigned to Bobj or not. It returns the address of the object, if it can, otherwise it will return 0.

So you can use it like:

B* BObj = dynamic_cast<B*>AObj;
if(BObj)
{
    //Now you can use it safely.
}
Nishant
  • 1,635
  • 1
  • 11
  • 24
  • Syntactically you've made a valid point and I'll edit my question accordingly.But it's the method access I'm a little hazy about.Thanks! – Vishnu Nair Aug 03 '15 at 08:42
  • @VishnuNair As Petr correctly pointed that this is Undefined Behavior and i meant the same when i said it is not safe, using BObj may or may not access B's function, or it can crash the code. – Nishant Aug 03 '15 at 08:53
  • @VishnuNair if dynamic_cast finds, it is safe to cast the object, it will cast and return the address, now in case there are additional functions defined in derived class, you would get a NULL. – Nishant Aug 03 '15 at 08:59