Interview Question
Developer Program EngineersCountry: United States
Interview Type: Written Test
if you see code more closely...,,
The class d1 & d2 both inherit base...
but only one is inheriting with virtual keyword >>Thats why the concept of virtual base class is not implemented...
hence...both d1 & d2 will have one-one copy of base,,,so two times...
Can anybody explain the reason? the behavior change when we change the order. Means inherit base for D1 virtual and inherit base for D2 non virtual. Or change the order when inheriting D1 and D2 for DD!
I tried to add the link to msdn's article, but the site is not allowing me to do that.
search for "virtual base classes msdn" in google and click the first link. That might help you. GOOD LUCK
#include<iostream>
using namespace std;
class A{
public:
A(){
cout << "In A\n";
}
};
class vB:virtual public A{
public:
vB(){
cout << "In vB\n";
}
};
class nvB: public A{
public:
nvB(){
cout << "In nvB\n";
}
};
class D1: public vB, public nvB{// A vB A nvB D1 , first base virtual
public:
D1(){
cout << "In D1\n";
}
};
class D2: public nvB, public vB{// A A nvB vB D2 , first base not virtual
public:
D2(){
cout << "In D2\n";
}
};
main(){
D1 d1;
D2 d2;
}
class D1: public vB, public nvB
Here output :
A (result of call to A() from D1)
vB (Does not call A() because vB is virtual)
A (result of call to A() from nvB, which is not virtual)
nvB
D1
class D2: public nvB, public vB
Output:
A (result of call to A() from D2)
A (result of call to A() from nvB, which is not virtual)
nvB
vB (Does not call A() because vB is virtual)
D2
Note:
Case 1: intermediate base classes are virtual and non-virtual
The most derived class(here D1 / D2) call the top-most Base class(here A), when any one of the intermediate base classes(here vB / nvB) is virtual.
Then non-virtual Base class also call the top-most Base
Case 2:
When all the intermediate base classes(here vB / nvB) are virtual, the most derived class(D1 / D2) will only call top-most base class(A)
Case 3:
When all the intermediate base classes(here vB / nvB) are non-virtual, then intermediate base classes call the top-most base class. In this case the most derived class(D1 / D2) does not call the top-most base class.
Two times....
- gnxtstar007 August 14, 2012if we add virtual in front of base in d1..
then only once !!