Inheritance is one of the foundational pillars of Object-Oriented Programming (OOP). In C++, it allows a class (called the derived or child class) to inherit properties and behaviors from another class (known as the base or parent class). This mechanism promotes the reusability of code, enabling developers to create a new class based on an existing one, inheriting its attributes and behaviors.
To help beginners test their understanding of C++ inheritance, here’s a quiz tailored just for you. Dive in, and after each question, you’ll find the correct answer with a concise explanation. Let’s see how much you know!
1. Which keyword is used to inherit a class in C++?
Answer:
Explanation:
In C++, inheritance is declared using one of the access specifiers: public, private, or protected.
2. Which type of inheritance leads to the diamond problem in C++?
Answer:
Explanation:
The diamond problem arises due to ambiguity when a class inherits from two classes that have a common base class. This occurs in multiple inheritance.
3. What is the type of inheritance where one class inherits from multiple classes?
Answer:
Explanation:
Multiple inheritance means a class can inherit properties and behaviors from more than one parent class.
4. By default, the members of the base class are _____ in the derived class.
Answer:
Explanation:
By default, the inherited members of a base class take the private access specifier in the derived class.
5. Which of the following can be inherited from the base class?
Answer:
Explanation:
In C++, derived classes inherit both public and protected members of the base class, but not its private members.
6. What is the type of inheritance where a derived class has only one base class?
Answer:
Explanation:
Single inheritance means that a class can inherit from only one base class.
7. In which type of inheritance do multiple derived classes share a single base class?
Answer:
Explanation:
In hierarchical inheritance, multiple derived classes share the same base class.
8. Which of the following cannot be inherited?
Answer:
Explanation:
In C++, constructors, destructors, and friend functions of the base class are not inherited by the derived class.
9. If the base class’s destructor is not virtual, what can happen?
Answer:
Explanation:
If the base class destructor is not virtual and a derived class object is deleted through a base class pointer, then the derived class’s destructor will not be called, leading to potential resource leaks.
10. When a derived class object is destroyed, which destructor is called first?
Answer:
Explanation:
When a derived class object is destroyed, the derived class destructor is called first, followed by the base class destructor.