C++ Class Inheritance Overriding and Returning a Derived Class

Description

C++ Class Inheritance Overriding and Returning a Derived Class

#include <iostream>
#include <string>
#include <map>

using namespace std;

class Product {/*from   ww w .j  av  a  2s  .co  m*/
public:
    string Name;
    int Price;
    int SerialNumber;
    Product(string aname, int aprice, int aserial) :
        Name(aname), Price(aprice),
        SerialNumber(aserial) {}
};
class Printer : public Product {
public:
    enum PrinterType {laser, inkjet};
    PrinterType Type;
    Printer(string aname, PrinterType atype, int aprice, int aserial) :
        Product(aname, aprice, aserial), Type(atype) {}
};

typedef map<string, Product *> ProductMap;

class ProductList {
public:
    ProductMap list;
    virtual Product *GetProductByName(string name);
    void AddProduct(string name, Product *per);
};

class PrinterList : public ProductList {
public:
    Printer *GetProductByName(string name);
};

Product *ProductList::GetProductByName
 (string name){
    return list[name];
}
void ProductList::AddProduct(
string name, Product *per) {
    list[name] = per;
}
Printer *PrinterList::GetProductByName(string name) {
    return static_cast<Printer *>(
        ProductList::GetProductByName(name));
}

int main(int argc, char *argv[])
{
    PrinterList list;
    list.AddProduct(string("A"),new Printer("A", Printer::laser,150, 1));
    list.AddProduct(string("B"),new Printer("B", Printer::inkjet,80, 5));
    Printer *myprinter = list.GetProductByName("B");

    if (myprinter != 0) {
        cout << myprinter->Price << endl;
    }
    return 0;
}



PreviousNext

Related