//C++ primer plus ...... chapter 15 page490
#include <iostream>
#include <string>
#include <new>
#include <functional>
using namespace std;
#if 1
//base class
class Item_base
{
public:
//constructor and destructor
Item_base(const string & book = "" , double sales_price=0.0)
:isbn(book),price(sales_price){}
virtual ~Item_base() {}
//common interface
string get_isbn() const { return isbn; }
double get_price() const {return price ;}
virtual double net_price(size_t n) const
{
cout << "Item_base." << __func__ << endl;
return n*price;
}
private:
string isbn;
protected:
double price;
};
//derived class
class Bulk_item : public Item_base {
public:
//constructor
Bulk_item(const string & str, double prc , size_t qty=5 , double discnt=0.2):
Item_base(str, prc) ,min_qty(qty),discount(discnt) { }
double net_price(size_t) const;
private:
size_t min_qty; //minimum quantity for discount
double discount;
};
double Bulk_item::net_price(size_t cnt) const
{
cout << "Bulk_item." << __func__ << endl;
if(cnt >= min_qty)
return cnt*(1 - discount)*price;
else
return cnt*price;
}
void print_books(ostream &os, const Item_base & item , size_t n)
{
os << "ISBN : " << item.get_isbn()
<< "\tprice : " << item.get_price()
<< "\tnumber :" << n
<< "\ttotal price : " << item.net_price(n)
<< endl << endl;
}
int main(int argc, char const *argv[])
{
double book_price = 2.99;
//base class object
Item_base book1("book1", book_price);
//derived class object
Bulk_item book2("boot2", book_price , 10, 0.1);
Item_base &ref_1 = book1;
print_books(cout , ref_1, 10);
//copy control , derived to base,
ref_1 = book2;
print_books(cout , ref_1, 100);
Item_base &ref_2 = book2;
print_books(cout , ref_2, 100);
return 0;
}
#endif
//makefile
TARGET = aaa
CC = gcc
CXX = g++
INCLUDES =
LIBS =
CFLAGS = -Wall -Werror
LINKFLAGS =
C_SOURCES = $(wildcard *.c)
C_OBJS = $(patsubst %.c, %.o, $(C_SOURCES))
CPP_SOURCES = $(wildcard *.cpp)
CPP_OBJS = $(patsubst %.cpp, %.o, $(CPP_SOURCES))
.c.o:
$(CC) -c -o $*.o $(CFLAGS) $(INCLUDES) $*.c
.cpp.o:
$(CXX) -c -o $*.o $(CFLAGS) $(INCLUDES) $*.cpp
compile: $(CPP_OBJS) $(C_OBJS)
$(CXX) $(LINKFLAGS) -o $(TARGET) $^ $(LIBS)
clean:
rm -f $(CPP_OBJS) $(C_OBJS)
rm -f $(TARGET)
uninstall:
rm -f $(TARGET)
rebuild: clean compile