dimanche 5 février 2017

Decorator pattern on the real example in C++

Hello I tried to implement "Decorator" pattern on the real example, but I can't decorate my object (Burger* b) in client side (in main function). When I type "new Cheese" in ConcretteBurger() - Visual Studio shows me an Error: "no defauls constructor exist for class "Cheese""

#include<iostream>
using namespace std;

class Burger{
public:
    virtual int get_cost() = 0;
};

class ConcretteBurger: public Burger{
public:
    int get_cost(){
        return 3;
    }
};

class BurgerDecorator:public Burger{
private:
    Burger *b;

public:
    BurgerDecorator(Burger* bb){
      bb = b;
    }
    ~BurgerDecorator(){
        delete b;
    }
    int get_cost(){
        return b->get_cost();
    }
};

class Tomato:public BurgerDecorator{
public:
    Tomato(Burger *b):BurgerDecorator(b){

    }
    int get_cost(){

        return BurgerDecorator::get_cost() + 4;
    }
};
class Cheese:public BurgerDecorator{
public:
    Cheese(Burger *b):BurgerDecorator(b){}
    int get_cost(){
        return BurgerDecorator::get_cost()+3;

    }
};

int main(){
     Burger* b = new ConcretteBurger(new Cheese);
     cout<<b->get_cost();

     system("pause");
}

Second problem that I didn't understood the concept :BurgerDecorator(b) after declaration of function. For example:

 Tomato(Burger *b):BurgerDecorator(b){}  

I didn't find it in C++ books .

Thank you

Aucun commentaire:

Enregistrer un commentaire