c++ inheritance example. easy example to understand inheritance in c++. public inheritance in c++.

Pv

 



First we will make a class with any name.
than we will make it's public members-
class cl{
    public:
    string name;
now we will make two functions in this class 
First function- 
    void tkna(){
        cout<<"ENTER YOUR NAME --> ";
        cin>>name;
        cout<<endl;
    }
the first function simply takes the user name.
Second function-
    void shna(){
        cout<<"YOUR NAME IS --> "<<name<<endl;
    }
the second function shows the name of user.
Now we will make a new class but, not as a normal class, we will write it as-
class cl1: public cl{

};
We will not write anything in this class.
Now we will work on main( ).
In our main program we will make a object of second class(cl1).
than we will run two function with the object we have created.
cl1 testing;
testing.tkna();
testing.shna();
This all we have to write.
So what we have done here?
we have inherit the members of first class and then used them in another class.
You can try this code by your own.

Full source code -
#include <iostream>
using namespace std;
class cl{
    public:
    string name;
    void tkna(){
        cout<<"ENTER YOUR NAME --> ";
        cin>>name;
        cout<<endl;
    }
    void shna(){
        cout<<"YOUR NAME IS --> "<<name<<endl;
    }
};
class cl1: public cl{

};
int main()
{
cl1 testing;
testing.tkna();
testing.shna();
return 0;
}
Tags

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*