Inheritance:-
Concept of
inheritance is like parent child relationship. It means taking some
properties from the parents. For example, If your father having black
eyes and your eyes are also black then it is called that color of
your eyes is inherited. If one class has borrowed some of properties
of main class so that class is called borrowed class and that class
who gives their properties to borrowed class is called main class. It
is also called relationship between classes.
In inheritance we
should know first about access specifiers.
Access specifier are
three types:-
1) Public members
2) Private members
3) Protected members
- If main class has
private members then those members are not accessible to
borrowed class.
- Protected
members are public to borrowed class but private to rest of the
program.
- Public members
are accessible to all.
When the access
specifier for the inherited main class is public then all public
members of the base class become public members of the borrowed
class.
If the access
specifier is private then all public members of the main class become
private members of the borrowed class.
The private members
of main class are in accessible to borrowed class. The public members
of the main class become private members to borrowed class but those
are accessible to borrowed class. If the access specifiers is not
present then it is taken as private by default.
For example:
#include<iostream.h>
class main
{
int a;
public:
void set a(int m)
{
a=m;
}
void show a()
{
cout<<”\na=
”<<a;
}
}; // inherit as
public
class borrowed :
public main
{
int b;
public :
void set b(int m)
{
b=m;
}
void show b()
{
cout<<”\nb=
”<<b;
}
};
void main()
{
borrowed obj; //
object of borrowed class
int a,b;
cout<<”\n
enter the value of a”;
cin>>a;
cout<<”enter
the value of b”;
cin>>b;
// using obj of
derived class base class member is accessed
obj.set a(a);
obj.set b(b);
// access member of borrowed class
obj.show a();
// access member of main class
obj.show b();
//access member of borrowed class
}
In the above program,
the obj is an object of borrowed class.Using obj we are accessing the
member function of main class. The borrowed class inherits main class
using an access specifier public.
Types of
Inheritance:-
1) single
2) Multiple
3) Multilevel
4) Hierarchical
Inheritance
5) Hybrid
Inheritance
We will discuss
these different types in next post.
Until then bye bye
!!!!
facebook: CLICK HERE!!!!!!!!!!
Twitter: @NewAgeInformers
Instagram: @new_age_informers_
Comments
Post a Comment