I get Linker errors in the following example if I keep the PointFactory member functions as non-static.
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
class Point {
private:
Point(const double x, const double y) :
x(x), y(y) {}
class PointFactory {
public:
static Point NewCartesian(double x, double y) {
return {x, y};
}
static Point NewPolar(double r, double theta) {
return {r*cos(theta), r*sin(theta)};
}
};
public:
double x, y;
// Needs to be friend coz stream object requires access to member variables
friend std::ostream& operator<<(std::ostream& os, Point const& obj) {
return os << "x: " << obj.x << " y: " << obj.y;
}
static PointFactory Factory;
};
int main() {
auto pt = Point::Factory.NewPolar(5, M_PI_4);
std::cout << pt << std::endl;
getchar();
return 0;
}
Why do I need PointFactory members to be static? What is the reasoning behind this?