Skip to content

Instantly share code, notes, and snippets.

@hallfox
Last active January 27, 2018 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hallfox/b2e62ea8788e3041dc57624159828b98 to your computer and use it in GitHub Desktop.
Save hallfox/b2e62ea8788e3041dc57624159828b98 to your computer and use it in GitHub Desktop.
A pure virtual class, notably because of methods that = 0 (also called "pure virtual" methods.) Classes that are pure virtual cannot be instantiated, only subclasses that implement the pure virtual methods can.
#include "Circle.h"
const double Circle::PI = 3.14;
Circle::Circle(double radius):
radius_(radius) {}
double Circle::area() const {
return _radius * _radius * PI;
}
#include "Shape.h"
class Circle: public Shape {
public:
Circle(double radius);
virtual double area() const override;
private:
double radius_;
static const double PI;
};
#include "Rectangle.h"
#include "Circle.h"
#include "Shape.h"
#include <iostream>
Shape* give_me_a_shape(int select) {
if (select >= 0) {
return new Rectangle(select + 1.0, select + 1.0);
}
return new Circle(-select);
}
int main(int argv, const char* argv[]) {
//Shape s1; // Can't be created because pure virtual, compile error
Rectangle r1;
// Compiler directly inserts call to Rectangle::area
std::cout << r1.area() << std::endl;
Shape& s2 = r1; // Ok
// ??
std::cout << s2.area() << std::endl;
Shape* s3 = give_me_a_shape(argv - 3);
// ??
std::cout << s3->area() << std::endl;
delete s3;
return 0;
}
#include "Rectangle.h"
Rectangle::Rectangle(double length, double width):
length_(length),
width_(width) {}
double Rectangle::area() const {
return length_ * width_;
}
#include "Shape.h"
class Rectangle: public Shape {
public:
Rectangle(double length, double width);
virtual double area() const override;
private:
double length_;
double width_;
};
class Shape {
public:
// Remember to make your destructors virtual kids
virtual ~Shape();
virtual double area() const = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment