Inheritance
Defination:
In General,Inheritance means that inherit something from parents like inherited property, inherits eyes color from your parents etc.In Programming , inheritance mean define a class in term of other class it will increase the Re-useability of functionality of that class thats why inheritance is very important in Object-Oreinted Programming Languages.
As i told you before inheritance is "Define a class in term of another class" what is that mean.It mean you already created a class and you wanna create a new one class having same members and attributes so are you going to create a new one instead of using these member function and attribute that you already have? Your Code must be Compact but comprehensive. So lets discuss about Base Class & Derived Class .
Base Class:
A class that you already created lets Suppose you have created a class name "A"
Derived Class:
A class that you just derived from base class we can call this relation "IS a" relation
because Derived class IS a part of Based class. i.e.. dog IS-A Animal, Cat is a black
Look at this Example:
"Dog is Inherited from Animal class"
Example with Program
"Addition.h" //header file//
#include<iostream>
using namespace std;
class A{
int a;
public:
void getval_a(int);
int get_a();
};
class B:public A{
int b,c;
public:
void getval_b(int);
void add();//c=b+get_a()
void disp_val();//cout<<c;
};
void A::getval_a(int x){
a=x;
}
int A::get_a(){
return a;
}
void B::getval_b(int x){
b=x;
}
void B::add(){
c=get_a()+b;
}
void B::disp_val(){
cout<<"Value of A: "<<get_a();
cout<<"\nValue of B: "<<b<<endl;
cout<<"Sum of A & B: "<<c;
}
//inheritance
"Addition.cpp"
#include<iostream>
#include"addition.h"
using namespace std;
int main()
{
int a,b;
B obj;
cout<<"Enter value of A"<<endl;
cin>>a;
cout<<"Enter value of B"<<endl;
cin>>b;
obj.getval_a(a);
obj.getval_b(b);
obj.add();
obj.disp_val();
}
"Main.cpp"
#include<iostream>
#include"addition.h"
using namespace std;
void A::getval_a(int x){
a=x;
}
int A::get_a(){
return a;
}
void B::getval_b(int x){
b=x;
}
void B::add(){
c=get_a()+b;
}
void B::disp_val(){
cout<<"Value of A: "<<get_a();
cout<<"\nValue of B: "<<b<<endl;
cout<<"Value of C: ";
}
0 comments:
Post a Comment