File tree Expand file tree Collapse file tree 4 files changed +90
-0
lines changed
Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Original file line number Diff line number Diff line change @@ -28,6 +28,8 @@ Examples include (and will expand to):
2828* Performance‑oriented C++ idioms
2929* Algorithms
3030 * [ integer-factorization] ( ./integer-factorization/ )
31+ * OOP
32+ * [ virtual-interface] ( ./virtual-interface/ )
3133
3234---
3335
Original file line number Diff line number Diff line change 1+ # pull in shared compiler settings
2+ include ../common.mk
3+
4+ # per-example flags
5+ # CXXFLAGS += -pthread
6+
7+ TARGET := $(notdir $(CURDIR ) )
8+ SRCS := $(wildcard * .cpp)
9+ OBJS := $(SRCS:.cpp=.o )
10+
11+ all : $(TARGET )
12+
13+ $(TARGET ) : $(OBJS )
14+ $(CXX ) $(CXXFLAGS ) -o $@ $^
15+
16+ % .o : % .cpp
17+ $(CXX ) $(CXXFLAGS ) -c $< -o $@
18+
19+ run : $(TARGET )
20+ ./$(TARGET ) $(ARGS )
21+
22+ clean :
23+ rm -f $(OBJS ) $(TARGET )
24+
25+ # Delegates to top-level Makefile
26+ check-format :
27+ $(MAKE ) -f ../Makefile check-format DIR=$(CURDIR )
28+
29+ .PHONY : all clean run check-format
Original file line number Diff line number Diff line change 1+ /* *
2+ This example shows the interface using virtual functions in C++.
3+ */
4+
5+ #include < iostream>
6+ #include < memory>
7+
8+ class Shape
9+ {
10+ public:
11+ virtual double
12+ area () const = 0 ; // Pure virtual function
13+ virtual ~Shape () {} // Virtual destructor
14+ };
15+
16+ class Circle : public Shape
17+ {
18+ private:
19+ double radius;
20+
21+ public:
22+ Circle (double r) : radius(r) {}
23+ double
24+ area () const override
25+ {
26+ return 3.14159 * radius * radius;
27+ }
28+ };
29+
30+ class Rectangle : public Shape
31+ {
32+ private:
33+ double width, height;
34+
35+ public:
36+ Rectangle (double w, double h) : width(w), height(h) {}
37+ double
38+ area () const override
39+ {
40+ return width * height;
41+ }
42+ };
43+
44+ int
45+ main ()
46+ {
47+ std::unique_ptr<Shape> shapes[2 ];
48+ shapes[0 ] = std::make_unique<Circle>(5.0 );
49+ shapes[1 ] = std::make_unique<Rectangle>(4.0 , 6.0 );
50+
51+ // The following line would cause a compilation error because Shape is an abstract class
52+ // Shape a = new Shape();
53+
54+ for (int i = 0 ; i < 2 ; ++i) {
55+ std::cout << " Area of shape " << i + 1 << " : " << shapes[i]->area () << std::endl;
56+ }
57+
58+ return 0 ;
59+ }
You can’t perform that action at this time.
0 commit comments