Avoid free functions (except operator functions) at file scope in .h files; avoid free functions with external linkage (including operator functions) in .cpp files.
- Free functions with user defined type arguments:
- Classes that holds utility functions as static member functions
- Prefer
scoped enum
tounscoped enum
- If
unscoped enum
is have to be used, define within class to keep the global namespace cleaner.
class MyClass
{
public:
enum Color {BLACK, RED, GREEN}
};
- Member or free inline functions should be defined in header files.
- Avoid preprocessor macros in header files except include guards
- const methods should not return non-const references or pointers
class MyClass
{
public:
B& GetB() const; // BAD
const B& GetB() const; // GOOD: Non-mutable
B& GetB(); // OK: Mutable
};
- Prefer
protected
methods rather thanprotected
fields: It is as bad aspublic
since it is giving access to its internals to its child class.
- Prefer modern style C++ casting over C style casting
dynamic_cast<T>(arg)
will not work if Copy Ctor is deleted or private for type ofarg
. (E0330, C2248)
- Implicit type conversion never happens on the implicit parameter,
this
, for member functions so considernon-member
overloading if implicit type conversion is desired. [Meyers - Effective C++, Item 24]
class MyClass
{
public:
MyClass(int){/*...*/}
const MyClass operator*(const MyClass &rhs){/*...*/};
};
auto obj = MyClass{};
auto result = obj * 2; // WORKS
auto result2 = 2 * obj; //ERROR - no implicit type conversion if not
- Implicit type conversion functions (also ctors) are never considered during template argument deduction.