Write a C++ program for implementing the inheritance concept.
Algorithm to solve the above problem:
1. Start the process.
2. Define the base class with variables and functions.
3. Define the derived class with variables and functions.
4. Get two values in main function.
5. Define the object for derived class in main function.
6. Access member of derived class and base class using the derived class object.
7. Stop the process.
Implementation of the above problem in C++:
#include<iostream>
using namespace std;
class base
{
public:
int x;
void set_x(int n)
{
x=n;
}
void show_x()
{
cout<<"\n Base class...";
cout<<"\n x="<<x;
}
};
class derived:public base
{
int y;
public:
void set_y(int n)
{
y=n;
}
void show_xy()
{
cout<<"\n Derived class...";
cout<<"\n x="<<x;
cout<<"\n y="<<y;
}
};
int main()
{
derived obj;
int x,y;
cout<<"\n Enter the value of x: ";
cin>>x;
cout<<"\n Enter the value of y: ";
cin>>y;
obj.set_x(x); // inherits the base class
obj.set_y(y); // access the member of derived class
obj.show_x(); // inherits the base class
obj.show_xy(); // access the member of derived class
return 0;
}
The output of the above program is tested on www.jdoodle.com
Output:
Enter the value of x:
Enter the value of y:
Base class...
x=10
Derived class...
x=10
y=20
Thanks
Mukesh Rajput
Post A Comment:
0 comments: