Skip to content

Commit 2fa9a1d

Browse files
committed
Adding delicated constructor example
1 parent d31e1ef commit 2fa9a1d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

C++11/delicated_constructors.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
}

0 commit comments

Comments
 (0)