diff --git a/M-cpp/code/Makefile b/M-cpp/code/Makefile new file mode 100644 index 0000000..5ae8507 --- /dev/null +++ b/M-cpp/code/Makefile @@ -0,0 +1,15 @@ +CC=g++ +CXX=g++ +CXXFLAGS=-g -Wall -std=c++11 +LDFLAGS= -g + +TARGS=cpp-basic-2 +default: $(TARGS) + +cpp-basic-2: +cpp-basic-2.o: + +clean: + rm -rf $(TARGS) *.o a.out + +.PHONY: default clean diff --git a/M-cpp/code/README.md b/M-cpp/code/README.md new file mode 100644 index 0000000..dde33c3 --- /dev/null +++ b/M-cpp/code/README.md @@ -0,0 +1,20 @@ +C++ Basic 2 Demo +================ + +This is a simple code demo that will show you when constructors and destructors +are called. + +Constructors are called when objects are declared and initialized, while +destructors are called at the end of the **block** an object is declared. +This is usually at the end of the curly brace that closes that block, +but this example demonstrates that it is also the case for the ends of one-liner +conditional and looping statements. + + +Building and running +-------------------- + +To build, type `make`. +To run, just run `./cpp-basic-2`. + +Feel free to modify the code as you wish to try out your own examples. diff --git a/M-cpp/code/cpp-basic-2.cpp b/M-cpp/code/cpp-basic-2.cpp new file mode 100644 index 0000000..ec144cc --- /dev/null +++ b/M-cpp/code/cpp-basic-2.cpp @@ -0,0 +1,43 @@ +#include +#include + +using namespace std; + +class Echoer { +public: + int id; + Echoer(int eid) { + id = eid; + cout << "constructor: " << id << endl; + } + + ~Echoer() { + cout << "destructor: " << id << endl; + } + + void echo() { + cout << "echoer: " << id << endl; + } +}; + +int main(void) +{ + Echoer e0 = Echoer(0); // created in main() block, not destroyed until end + + { // new block + Echoer e1 = Echoer(1); + } // end block, e1 destructor called + + if (1) + Echoer e2 = Echoer(2); + // there is an implicit block at the end of one-liner conditionals + // even if there is no end curly brace + + int i; + for (i = 3; i < 6; i++) + Echoer ei = Echoer(i); + // same with one-liner looping statements + // each ei will be destroyed before the next iteration + + return 0; +} // end of main() block, e0 destroyed here