1- C# Interface
public interface IShape
{
double Area();
double Perimeter();
}
2- C# Implementation (Rectangle)
public class Rectangle : IShape
{
private readonly double width;
private readonly double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double Area() => width * height;
public double Perimeter() => 2 * (width + height);
}
3- Using the C# interface
IShape shape = new Rectangle(3.0, 4.0);
Console.WriteLine($"Area: {shape.Area()}");
Console.WriteLine($"Perimeter: {shape.Perimeter()}");
A- C++ Interface (pure abstract class)
class IShape {
public:
virtual ~IShape() = default;
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
B- C++ Implementation of the Interface
class Rectangle : public IShape {
public:
Rectangle(double width, double height)
: w_(width), h_(height) {}
double area() const override {
return w_ * h_;
}
double perimeter() const override {
return 2 * (w_ + h_);
}
private:
double w_;
double h_;
};
C- Using the Interface in C++
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<IShape> shape = std::make_unique<Rectangle>(3.0, 4.0);
std::cout << "Area: " << shape->area() << "\n";
std::cout << "Perimeter: " << shape->perimeter() << "\n";
}
