Goldman Sachs Interview Question
Software Engineer / Developersif you want to get away from the compile time error use reinterpret_cast as below.
A &a =reinterpret_cast<A&>(b);
@ Please ignore above Qn. here is correct one
output of following Program
class A
{
int n;
public:
virtual void Fun1(int no=10)
{
n = no;
cout<<"A::Fun1"<<n;
}
};
class B
{
int m;
public:
virtual void Fun1(int no=20)
{
m = no;
cout<<"B::Fun1()"<<m;
}
}
int main()
{
B b;
A &a =b;
a.Fun1();
}
Looks like they forgot inheritance in the above code. If B is inherited from A then the output is B::Func1.a The confusing part is what happens if its not a reference and just an object of A ?
ie., A a = b; /// in this class object gets sliced and caling
a.func1() would result int A::Func1..
No, the reason behind this is
B b;
A &a =b;
a.Fun1();
function resolution happens at run time. hence a.Func1() will invoke the derived class Func1(). i.e., dynamic binding. whereas the initialization of the variable happens at the compile time.
So at compile time
a.Func1() will have references to Base class Func1
virtual void Func1(int no=10)
{
n = no;
cout<<"A::Fun1"<<n;
}
and hence no=10.
Functions are dynamically bind in case of virtual but the default parameter values are statically bind. Refer More Effective C++.
It gives compile time error: can not convert from B to A&
- BM February 19, 2011