diff --git a/README.md b/README.md index 061480d..8acd9b0 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ Examples include (and will expand to): * Performance‑oriented C++ idioms * Algorithms * [integer-factorization](./integer-factorization/) +* OOP + * [virtual-interface](./virtual-interface/) --- diff --git a/virtual-interface/Makefile b/virtual-interface/Makefile new file mode 100644 index 0000000..6e5fc0f --- /dev/null +++ b/virtual-interface/Makefile @@ -0,0 +1,29 @@ +# pull in shared compiler settings +include ../common.mk + +# per-example flags +# CXXFLAGS += -pthread + +TARGET := $(notdir $(CURDIR)) +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 diff --git a/virtual-interface/main.cpp b/virtual-interface/main.cpp new file mode 100644 index 0000000..0742a85 --- /dev/null +++ b/virtual-interface/main.cpp @@ -0,0 +1,59 @@ +/** + This example shows the interface using virtual functions in C++. +*/ + +#include +#include + +class Shape +{ + public: + virtual double + area() const = 0; // Pure virtual function + virtual ~Shape() {} // Virtual destructor +}; + +class Circle : public Shape +{ + private: + double radius; + + public: + Circle(double r) : radius(r) {} + double + area() const override + { + return 3.14159 * radius * radius; + } +}; + +class Rectangle : public Shape +{ + private: + double width, height; + + public: + Rectangle(double w, double h) : width(w), height(h) {} + double + area() const override + { + return width * height; + } +}; + +int +main() +{ + std::unique_ptr shapes[2]; + shapes[0] = std::make_unique(5.0); + shapes[1] = std::make_unique(4.0, 6.0); + + // The following line would cause a compilation error because Shape is an abstract class + // Shape a = new Shape(); + + for (int i = 0; i < 2; ++i) { + std::cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() << std::endl; + } + + return 0; +} \ No newline at end of file diff --git a/virtual-interface/virtual-interface b/virtual-interface/virtual-interface new file mode 100755 index 0000000..67098f0 Binary files /dev/null and b/virtual-interface/virtual-interface differ