C++: Simple inheritance - Applications solved
1) Example class hierarchy (redeclaration of member data and member functions overloading of classes in the derived class).
#include <iostream> using namespace std; #include<conio.h> #include<stdlib.h> #include<math.h> #include <fstream> class number { protected: int n; public: void display(char* s) { cout<<"the number "<<s<<" is: "<<n<<endl; } int retur() { return n; } }; class number_d1: public number { public: void read(char *s) { cout<<"Read the number "<<s<<endl; cout<<"\tn="; cin>>n; } void add(number_d1 a, number b) { n=a.n+b.retur(); } }; class number_d2: public number_d1 { //being introduced once personal and retention required number square it said in previous int n; public: number_d2 operator*() { number_d2 a; a.n=(number::n+2); return a; } void display() { cout<<"The desired result is (I added 2 of the result): "<<n<<endl; } }; void main() { number_d2 a,b,c; a.read("a"); b.read("b"); c.add(a,b); c.number_d1::display("a+b"); number_d2 d; d=*c; d.display(); int k; cin>>k; }
2) Example builders in class hierarchies.
#include <iostream> using namespace std; class number { protected: int n; public: number(int a=5) { n=a; cout<<"Base class constructor.\n"; } int& retur() { return n; } friend ostream& operator<<(ostream& out,number a) { out<<"The number is: "<<a.n<<endl; return out; } }; class number_d: public number { public: number_d(int a=10):number(a) /* :number (a) is not necessarily required to write, this is done when we have more constructors in the base class */ { cout<<"Derived class constructor.\n"; n=a; } /* - An object from a base class can be assigned to an object of a class that is derived from it - An object of a derived class can not assign a base class object as a class derivative is a supplement to a base class and not vice versa (But we can equip a derived class method achieved by overloading the operator "=". But here belongexclusive data derived class take arbitrary values??.) */ void operator=(number & x) { n=x.retur(); } }; void main() { number a; cout<<a; number_d b; cout<<b; b=a; //this would not have been possible without overloading operator = cout<<b; int k; cin>>k; }