Tell me when you should use virtual inheritance?
Submitted by: MuhammadWhile it’s ideal to avoid virtual inheritance altogether (you should know how your class is going to be used) having a solid understanding of how virtual inheritance works is still important:
So when you have a class (class A) which inherits from 2 parents (B and C), both of which share a parent (class D), as demonstrated below:
#include <iostream>
class D {
public:
void foo() {
std::cout << "Foooooo" << std::endl;
}
};
class C: public D {
};
class B: public D {
};
class A: public B, public C {
};
int main(int argc, const char * argv[]) {
A a;
a.foo();
}
If you don’t use virtual inheritance in this case, you will get two copies of D in class A: one from B and one from C. To fix this you need to change the declarations of classes C and B to be virtual, as follows:
class C: virtual public D {
};
class B: virtual public D {
};
Submitted by: Muhammad
So when you have a class (class A) which inherits from 2 parents (B and C), both of which share a parent (class D), as demonstrated below:
#include <iostream>
class D {
public:
void foo() {
std::cout << "Foooooo" << std::endl;
}
};
class C: public D {
};
class B: public D {
};
class A: public B, public C {
};
int main(int argc, const char * argv[]) {
A a;
a.foo();
}
If you don’t use virtual inheritance in this case, you will get two copies of D in class A: one from B and one from C. To fix this you need to change the declarations of classes C and B to be virtual, as follows:
class C: virtual public D {
};
class B: virtual public D {
};
Submitted by: Muhammad
Read Online C++ Programmer Job Interview Questions And Answers
Top C++ Programmer Questions
☺ | Explain me what is an Object/Instance? |
☺ | Explain void free (void* ptr)? |
☺ | Tell me how to create a pure virtual function? |
☺ | Tell me what will the line of code below print out and why? |
☺ | Please explain is there a difference between class and struct? |
Top C Plus Plus Language Categories
☺ | C++ Pointers & Functions Interview Questions. |
☺ | C++ Operator Overloading Interview Questions. |
☺ | C++ Exception Handling Interview Questions. |
☺ | C++ Virtual Functions Interview Questions. |
☺ | C++ Template Interview Questions. |