Advance Interview Ask In C++ Interview #4
How to stop class inheritance in C++ with condition that object creation should be allowed Answer includes multiple solutions to stop or prevent class inheritance in C++ with condition that object creation of the class should be allowed with C++ program example and explanation. Interview Question: I want to stop a class to be inherited and allow to create an object of the class. Design a solution for this problem statement. Give as many solutions as you can. Answer: We can apply 3 solutions to prevent a class to be inherited in C++ where object creations will be allowed. Solution-1: Use the final keyword (from C++11) In the below example, we’ve made the Unique class final. So, it’ll not be inherited by any class. If you try to inherit it, the compiler will flash an error that “ a final class cannot be used as a base class “. Note that you can create an object of the final class as show in the main() method here. #include <iostream> using namespace std; class Unique final...