File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * 2. DELIGATED CONSTRUCTORS:
3+ *
4+ * The following code implements the idea of deligated constructors first introfuced in C++11
5+ * This allows an overloaded constructor to avoid code duplication and by deligating some
6+ * of the work to another constructor of the same class
7+ */
8+ #include < iostream>
9+ #include < cassert>
10+ #include < sstream>
11+
12+ class Foo
13+ {
14+ public:
15+ Foo ()
16+ {
17+ a = b = c = 1 ;
18+ }
19+ // By extending the default constructor, we delicate part of the work that needs to be done
20+ Foo (int c) : Foo()
21+ {
22+ this ->c = c;
23+ }
24+
25+ private:
26+ int a;
27+ int b;
28+ int c;
29+
30+ friend std::ostream& operator <<(std::ostream& o, const Foo& f)
31+ {
32+ o << " (" << f.a << " ," << f.b << " ," << f.c <<" )\n " ;
33+ return o;
34+ }
35+ };
36+
37+ int main ()
38+ {
39+ std::cout << " ===== Test : Deligated constructor was called =====\n " ;
40+ Foo default_constr;
41+
42+ std::ostringstream oss;
43+ oss << default_constr;
44+ assert (oss.str () == " (1,1,1)\n " );
45+
46+ // Resetting ostring stream
47+ oss.str (std::string ());
48+
49+ Foo deligated_constr (3 );
50+ oss << deligated_constr;
51+ assert (oss.str () == " (1,1,3)\n " );
52+
53+ return 0 ;
54+ }
You can’t perform that action at this time.
0 commit comments