| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 15:54:04 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 16:04:04 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=F1VD5F%2FOSaHWNfxyxMaDcstTQ8m6FqpqIyMCzg%2B%2BksLQDmK6SJgGkmexBXaiq77YvAHAZCGxU8Qp4nrCAjAYq05vuKqJgT5qkrQE7fd3KQ%3D%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 2457:377A95:6831496:7412881:6953F59C
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b62b6af697b3501-BOM
alt-svc: h3=":443"; ma=86400
Decorator - C++ Patterns
← Patterns
Decorator
12345678910111213141516171819202122232425262728293031323334353637383940414243 | class foo
{
public:
virtual void do_work() = 0;
};
class foo_concrete : public foo
{
public:
virtual void do_work() override
{ }
};
class foo_decorator : public foo
{
public:
foo_decorator(foo& f)
: f(f)
{ }
virtual void do_work() override
{
// Do something else here to decorate
// the do_work function
f.do_work();
}
private:
foo& f;
};
void bar(foo& f)
{
f.do_work();
}
int main()
{
foo_concrete f;
foo_decorator decorated_f{f};
bar(decorated_f);
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Requires
c++98
or newer.
Intent
Extend the functionality of a class.
Description
On lines 7–12, we define the class that we wish to decorate,
foo_concrete, which implements the foo interface.
The foo_decorator class, on lines 14–29, also implements the
foo interface. This decorator class wraps any other foo
object, and forwarding any calls to the wrapped object. By adding
additional code to foo_decorator::do_work (lines 21–25), we can
extend the functionality of the wrapped object.
To demonstrate, we wrap a foo_concrete with a foo_decorator on
lines 38–39, and pass it to the bar function on line 41, which takes a
reference to any foo object and calls do_work on it. In this
case, the call will be decorated by foo_decorator.
