Skip to content

Instantly share code, notes, and snippets.

@naoki-mizuno
Created March 27, 2018 11:24
Show Gist options
  • Save naoki-mizuno/e0d91ed981c3fe6a25a6ed28717af438 to your computer and use it in GitHub Desktop.
Save naoki-mizuno/e0d91ed981c3fe6a25a6ed28717af438 to your computer and use it in GitHub Desktop.
Default argument ctor is bad
#include <iostream>
/*
* This program illustrates why using default arguments in a constructor is
* bad. Without explicitly defining an operator+(const float k), a Vector2D
* with y being 0 is created.
*/
struct Vector2D {
/// default constructor
inline Vector2D(const float x = 0, const float y = 0) { this->x = x; this->y = y; }
// inline Vector2D operator + (const float k) const { return Vector2D(x + k, y + k); }
// inline Vector2D operator - (const float k) const { return Vector2D(x - k, y - k); }
inline Vector2D operator * (const float k) const { return Vector2D(x * k, y * k); }
inline Vector2D operator / (const float k) const { return Vector2D(x / k, y / k); }
inline Vector2D operator + (const Vector2D& b) const { return Vector2D(x + b.x, y + b.y); }
inline Vector2D operator - (const Vector2D& b) const { return Vector2D(x - b.x, y - b.y); }
inline Vector2D operator - () const {return Vector2D(-x, -y);}
friend std::ostream& operator<<(std::ostream& os, const Vector2D& b) {os << b.x << ", " << b.y; return os; }
float x;
float y;
};
int
main() {
auto va = Vector2D(3, 2);
// Intuitively an error, but valid because of default arguments in ctor
auto vb = Vector2D(3);
auto vc = Vector2D();
std::cout << va << std::endl;
std::cout << vb << std::endl;
std::cout << vc << std::endl;
// Expected: (5, 4), Actual: (5, 2)
std::cout << (va + 2) << std::endl;
// Doesn't make sense
std::cout << (vb + 2) << std::endl;
// Expected: (2, 2), Actual: (2, 0)
std::cout << (vc + 2) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment