The below code attempts to implement basic Decorator Design Pattern using references to refer to the base component class Paragraph
#include <string>
#include <iostream>
using std::cout; using std::endl; using std::string;
// component
class Paragraph{
public:
Paragraph(const string& text = "") : text_(text) {}
virtual string getHTML() const { return text_; }
private:
const string text_;
};
// first decorator
class BoldParagraph : public Paragraph {
public:
BoldParagraph(const Paragraph& wrapped): wrapped_(wrapped) {}
string getHTML() const override {
return "<b>" + wrapped_.getHTML() + "</b>";
}
private:
const Paragraph &wrapped_;
};
// second decorator
class ItalicParagraph : public Paragraph {
public:
ItalicParagraph(const Paragraph& wrapped): wrapped_(wrapped) {}
string getHTML() const override {
return "<i>" + wrapped_.getHTML() + "</i>";
}
private:
const Paragraph &wrapped_;
};
int main(){
Paragraph p("Hello, World!");
BoldParagraph bp(p); cout << bp.getHTML() << endl;
BoldParagraph bbp(bp); cout << bbp.getHTML() << endl;
ItalicParagraph ibp(bp); cout << ibp.getHTML() << endl;
}
When run, it produces
<b>Hello, World!</b>
<b>Hello, World!</b>
<i><b>Hello, World!</b></i>
rather than
<b>Hello, World!</b>
<b><b>Hello, World!</b></b>
<i><b>Hello, World!</b></i>
That is, the second wrapped function getHML() appears to be skipped if it is for the same subclass BoldParagraph for object bbp, but not if it is for different subclasses ItalicParagraph and BoldParagraph for object ibp. Similar code with pointers rather than references works as expected.
why is that?