C++ examples for Class:Inheritance
Multiple inheritance with English Measures
#include <iostream> #include <string> using namespace std; class Type //type of lumber { private:/*from w w w . j a v a 2 s . co m*/ string dimensions; string grade; public: //no-arg constructor Type() : dimensions("N/A"), grade("N/A") { } //2-arg constructor Type(string di, string gr) : dimensions(di), grade(gr) { } void gettype() //get type from user { cout << " Enter nominal dimensions (2x4 etc.): "; cin >> dimensions; cout << " Enter grade (rough, const, etc.): "; cin >> grade; } void showtype() const { cout << "\n Dimensions: " << dimensions; cout << "\n Grade: " << grade; } }; class Measure { private: int feet; float inches; public: //no-arg constructor Measure() : feet(0), inches(0.0) { } Measure(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << " Enter feet: "; cin >> feet; cout << " Enter inches: "; cin >> inches; } void showdist() const { cout << feet << "\'-" << inches << '\"'; } }; class Product : public Type, public Measure { private: int quantity; //number of pieces double price; //price of each piece public: Product() : Type(), Measure(), quantity(0), price(0.0) { } //constructor (6 args) Product( string di, string gr, int ft, float in, int qu, float prc ) : Type(di, gr), Measure(ft, in), //call Measure ctor quantity(qu), price(prc) //initialize our data { } void getlumber() { Type::gettype(); Measure::getdist(); cout << " Enter quantity: "; cin >> quantity; cout << " Enter price per piece: "; cin >> price; } void showlumber() const { Type::showtype(); cout << "\n Length: "; Measure::showdist(); cout << "\n Price for " << quantity << " pieces: $" << price * quantity; } }; int main() { Product siding; cout << "\nSiding data:\n"; siding.getlumber(); //get siding from user //constructor (6 args) Product studs( "2x4", "const", 8, 0.0, 200, 4.45F ); cout << "\nSiding"; siding.showlumber(); cout << "\nStuds"; studs.showlumber(); cout << endl; return 0; }