In this blog we will learn
what is inheritence and we will also learn how to use.
this is my code which we have to run in the compiler so go to your
compiler and run this program and check this........
// C++ program to demonstrate inheritance
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
// Calling members of the base class
dog1.eat();
dog1.sleep();
// Calling member of the derived class
dog1.bark();
return 0;
}
this is the code you have to understant this.
Here i will provide some explaination in this blog so that you can understand this i think its useful for the student.
Notice the use of the keyword public while inheriting Dog from Animal.
class Dog : public Animal {...};
We can also use the keywords private and protected instead of public. We will learn about the differences between using private, public and protected later in this tutorial.
is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the two classes.
Here are some examples:
- A car is a vehicle.
- Orange is a fruit.
- A surgeon is a doctor.
- A dog is an animal.
टिप्पणियाँ
एक टिप्पणी भेजें