Skip to content
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Examples include (and will expand to):
* [rot47](./rot47/)
* OOP
* [virtual-interface](./virtual-interface/)
* [oop-with-exception](./oop-with-exception/)

---

Expand Down
31 changes: 31 additions & 0 deletions oop-with-exception/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# pull in shared compiler settings
include ../common.mk

# per-example flags
# CXXFLAGS += -pthread

## get it from the folder name
TARGET := $(notdir $(CURDIR))
## all *.cpp files in this folder
SRCS := $(wildcard *.cpp)
OBJS := $(SRCS:.cpp=.o)

all: $(TARGET)

$(TARGET): $(OBJS)
$(CXX) $(CXXFLAGS) -o $@ $^

%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@

run: $(TARGET)
./$(TARGET) $(ARGS)

clean:
rm -f $(OBJS) $(TARGET)

# Delegates to top-level Makefile
check-format:
$(MAKE) -f ../Makefile check-format DIR=$(CURDIR)

.PHONY: all clean run check-format
47 changes: 47 additions & 0 deletions oop-with-exception/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
This example creates two classes A and B, where class B is a member of class A.
And in the constructor of class A, it prints a message and throws an exception.
So what would be the output?

B's constructor called.
A's constructor called.
B's destructor called.
Caught exception: Exception in A's constructor

If an exception leaves a constructor, the object’s destructor does not run, because the object never finished
construction. But destructors for already-constructed members/base-subobjects do run.
*/

#include <iostream>
#include <stdexcept>

class B
{
public:
B() { std::cout << "B's constructor called." << std::endl; }
~B() { std::cout << "B's destructor called." << std::endl; }
};

class A
{
private:
B b; // Member of class B
public:
A()
{
std::cout << "A's constructor called." << std::endl;
throw std::runtime_error("Exception in A's constructor");
}
~A() { std::cout << "A's destructor called." << std::endl; }
};

int
main()
{
try {
A a; // Attempt to create an instance of A
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
Binary file added oop-with-exception/oop-with-exception
Binary file not shown.
5 changes: 5 additions & 0 deletions oop-with-exception/tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

set -ex

./oop-with-exception