Single Inheritence In C++
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
{
// body of the derived class.
}
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
- When the base class is privately inherited by the derived class, public members of the base class becomes the private members of the derived class. Therefore, the public members of the base class are not accessible by the objects of the derived class only by the member functions of the derived class.
- When the base class is publicly inherited by the derived class, public members of the base class also become the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the derived class as well as by the member functions of the base class.
Note:
- In C++, the default mode of visibility is private.
- The private members of the base class are never inherited.
C++ Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.Where 'A' is the base class, and 'B' is the derived class.
C++ Single Level Inheritance Example: Inheriting Fields
When one class inherits another class, it is known as single level inheritance. Let's see the example of single level inheritance which inherits the fields only.- #include <iostream>
- using namespace std;
- class Account {
- public:
- float salary = 60000;
- };
- class Programmer: public Account {
- public:
- float bonus = 5000;
- };
- int main(void) {
- Programmer p1;
- cout<<"Salary: "<<p1.salary<<endl;
- cout<<"Bonus: "<<p1.bonus<<endl;
- return 0;
- }
Salary: 60000
Bonus: 5000
C++ Single Level Inheritance Example: Inheriting Methods
Let's see another example of inheritance in C++ which inherits methods only.- #include <iostream>
- using namespace std;
- class Animal {
- public:
- void eat() {
- cout<<"Eating..."<<endl;
- }
- };
- class Dog: public Animal
- {
- public:
- void bark(){
- cout<<"Barking...";
- }
- };
- int main(void) {
- Dog d1;
- d1.eat();
- d1.bark();
- return 0;
- }
Comments
Post a Comment