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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Examples include (and will expand to):
* Performance‑oriented C++ idioms
* Algorithms
* [integer-factorization](./integer-factorization/)
* OOP
* [virtual-interface](./virtual-interface/)

---

Expand Down
29 changes: 29 additions & 0 deletions virtual-interface/Makefile
Original file line number Diff line number Diff line change
@@ -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
59 changes: 59 additions & 0 deletions virtual-interface/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
This example shows the interface using virtual functions in C++.
*/

#include <iostream>
#include <memory>

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<Shape> shapes[2];
shapes[0] = std::make_unique<Circle>(5.0);
shapes[1] = std::make_unique<Rectangle>(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;
}
Binary file added virtual-interface/virtual-interface
Binary file not shown.