C++

Subpages

int*p or int *p?

Bjarne Stroustrup says:

A typical C programmer writes int *p; and explains it *p is what is the int emphasizing syntax.
A typical C++ programmer writes int* p; and explains it p is a pointer to an int emphasizing type. He clearly prefer this emphasis.

See also: StackOverflow difference-between-char-var-and-char-var

Order of #include directives

  1. h file corresponding to this cpp file (if applicable)
  2. Other headers from the same project, as needed (Local headers)
  3. Headers from other non-standard, non-system libraries (for example, Qt)
  4. Headers from other “almost-standard” libraries (for example, Boost)
  5. Standard C++ headers (for example, iostream, functional, etc.)
  6. Standard C headers (for example, cstdint, dirent.h, etc.)

Prefixes on member variables

There are several possibilities in naming member variables.

  • Hungarian notation
  • prefixes done well (m for member, c for constant, p for pointer, …)
  • m_ prefix
  • no prefix (Stroustrup, e.g. page 455)
  • use this->
  • leading (prefix) underscore (may be reserved, Stroustrup page 155)
  • postfix underscore (Google C++ Style)

See: stackoverflow why-use-prefixes-on-member-variables-in-c-classes

Note that Python or Ruby enforce the their own prefix, Ruby uses @ for member variables and Python requires self.

new or new()?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don’t mind if the constructor isn’t called.
In all versions of C++ there’s a difference between new A and new A() because A is a POD.
And there’s a difference in behavior between C++98 and C++03 for the case new B().

Do the parentheses after the type name make a difference with new?

void foo() or void foo(void)?

void foo();

Means different things in C and C++! In C it means “could take any number of parameters of unknown types”, and in C++ it means the same as foo(void).

Inheritance class D : B

class derived-class: access-specifier base-class

Default access-specifier is private.

https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm

Exception Specifications

Throw keyword in a function signature.

int f() throw();
int g() throw(A,B);

In C++ 11, the noexcept keyword was added as both operator and specifier (cppreference.com). The operator noexcept( expression ) returns a prvalue of type bool.

void f() noexcept; // the function f() does not throw
void (*fp)() noexcept(false); // fp points to a function that may throw

Class Template

As far as C++ is concerned, there is no such thing as a “template class,” there is only a “class template.” (StackOverflow)

Links