diff options
author | Kamil Kaminski <kylek389@gmail.com> | 2014-02-28 08:31:36 -0600 |
---|---|---|
committer | Kamil Kaminski <kylek389@gmail.com> | 2014-02-28 08:31:36 -0600 |
commit | 88118d727819b4d42c0e1f8b742e80b517b21939 (patch) | |
tree | 2d1ee3144a729174231e3f813ef8ae748e4f79cb /inheritance_ctor_calls.cpp | |
parent | e8244aab814168304da11283b52608c81f75d346 (diff) | |
download | c++-88118d727819b4d42c0e1f8b742e80b517b21939.tar.gz c++-88118d727819b4d42c0e1f8b742e80b517b21939.tar.bz2 c++-88118d727819b4d42c0e1f8b742e80b517b21939.zip |
Diffstat (limited to 'inheritance_ctor_calls.cpp')
-rw-r--r-- | inheritance_ctor_calls.cpp | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/inheritance_ctor_calls.cpp b/inheritance_ctor_calls.cpp new file mode 100644 index 0000000..6d692a8 --- /dev/null +++ b/inheritance_ctor_calls.cpp @@ -0,0 +1,77 @@ +/* g++ -Wall -std=gnu++98 -pedantic -MD -O0 -g inheritance_ctor_calls.cpp -o inheritance_ctor_calls + * + * Note: line 64 is very IMPORTANT! + * output: + * + * node1 default ctor called + * node2 default ctor called with y + * node1 default ctor called + * node2 copy ctor called + * + */ + +#include <iostream> + +class Node1 +{ + public: + Node1() : x_(0) { + std::cout << "node1 default ctor called\n"; + }; + Node1(int x) : x_(x) { + std::cout << "node1 default ctor called with x\n"; + }; + + virtual void foo() { + std::cout << "node1 foo called\n"; + } + + int x_; +}; + +class Node2 : public Node1 +{ + public: + Node2() : y_(0) { + std::cout << "node2 default ctor called\n"; + }; + Node2(int y) : y_(y) { + std::cout << "node2 default ctor called with y\n"; + }; + + Node2(const Node2 &n) : y_(0) { + std::cout << "node2 copy ctor called\n"; + } + + virtual void foo() { + std::cout << "node2 foo called\n"; + /* invoke parent method */ + Node1::foo(); + /* do things unique to this class */ + /* ... */ + } + + int y_; +}; + +class Collection : public Node2 +{ + public: + /* only immediate base class may be initialized, Node1 is 2 level deep here hence error */ + Collection() : /* Node1(2), error */ Node2(1), z(0) { + } + /* parent copy ctor needs to be invoked since derived class' copy ctor is overridden */ + Collection(const Collection& c) : Node2(c), z(0) { + /* ... */ + } + + int z; +}; + +int main(int argc, char **argv) +{ + Collection c; + Collection d(c); + + return 0; +} |