Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cpp basic 2 demo #128

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions M-cpp/code/Makefile
Original file line number Diff line number Diff line change
@@ -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
20 changes: 20 additions & 0 deletions M-cpp/code/README.md
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 43 additions & 0 deletions M-cpp/code/cpp-basic-2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <cstdio>
#include <iostream>

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