Correct option is B
In C++,
inheritance is implemented using the following syntax:
class derived_classname : access base_classname {
// Define class body
};
Here’s what each component represents:
· class derived_classname: Declares a new class that will
inherit properties from another class.
· access base_classname: Specifies the
access specifier (public, protected, or private) followed by the base class from which the new class is inheriting.
· { /*define class body*/ }: Contains the member functions and variables of the derived class.
Since
option (b) correctly follows this syntax, it is the correct answer.
Important Key Points:
1.
Types of Inheritance in C++:
·
Public Inheritance (public base_class) → Keeps inherited members with the same access levels.
·
Protected Inheritance (protected base_class) → Makes inherited members protected.
·
Private Inheritance (private base_class) → Makes inherited members private.
2.
Correct Syntax Explanation:
· The base class is specified
after the colon (:) in the derived class declaration.
· An
access specifier is required (public, protected, or private).
· Example:
class Parent {
public:
int x;
};
class Child : public Parent {
// x is inherited as public
};
3.
Example of Correct Inheritance Usage:
class Animal {
public:
void sound() { cout << "Animal makes a sound"; }
};
class Dog : public Animal {
public:
void bark() { cout << "Dog barks"; }
};
· Here,
Dog inherits from Animal, so it can access the sound() function.
4.
Use of Access Specifiers in Inheritance:
·
Public Inheritance: Keeps members as they are.
·
Protected Inheritance: Makes all public members
protected.
·
Private Inheritance: Makes all inherited members
private.
Knowledge Booster:
·
class base_classname : access derived_classname Incorrect: Because the base class should be mentioned after the colon (:), not the derived class. The
base class should come after the colon (:), not the derived class. class base_classname : access derived_classname {...}; is an incorrect order.
·
class derived_classname : base_classname: Lacks an access specifier, which defaults to private inheritance in C++. It
does not specify an access specifier, which can lead to unintended behavior. In C++, if no access specifier is mentioned, the default is
private inheritance for classes.