- Neither C nor C++ are type-safe. One
memcpy
call and you can put anything in memory meant for some other type. - References (e.g.
int& something
) are C++ only. They are effectively constant final pointers.int& c = a;
means "C points to whatever A is already pointing to", which is safer, and simpler to understand. - Creating a reference to something uninitialised may accidentally give it value.
int a; int& b = a;
will suddenly makea
nonzero. Use-Wuninitialized
(part of-Wall
) to detect this error. - It is impossible to write
int& something;
. You must assign it something on initialisation. - "Member-access with pointers uses
->
; member-access with references uses.
- The
~ClassName
definition in a class denotes a destructor, becauseClassName
initially is a constructor, but negated by~
to give the semantic meaning of a destructor. public:
followed by an indented block of methods, means that anything inside the block is public (same applies toprivate
)
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {
return width*height;
}
}; // semicolon?
- Trigraphs are character mappings that map three characters to a single one, not found on older keyboards. For example, "??!" maps to "|".
- You are supposed to use Smart pointers now (C++11), which manages memory allocation for you. You should never (supposedly) create references to objects like in C# and Java either; just create objects and C++ will manage the memory for you.
- Operators can be overloaded; for example, to overload
+
for adding twoClass
es together, useClass operator+(const Class&, const Class&);
- Function overloading is not a standard feature in C, but you can do it in C11 in an ugly way.
- Ugly (yet valid) C syntax:
- Inline return type definitions are possible:
struct foo {...} function () { return foo(...) }
- Returning pointers to functions, where
foo
takes in nothing, and returns a functionbar
that takes an int and returns an int:int ( *foo(void) ) (int i) { return bar }
"Hello"[5] == 5["Hello"]
.
- Inline return type definitions are possible:
- You can still specify the namespace,
foo::some_func()
, in a file/methodusing namespace foo
. std::cout
is more proper thanprintf
in C++.- If your header files are C++ only, name them
.hpp
. Otherwise, header files that can be used for both C and C++ should use.h
. - C++ struct values can have defaults:
struct Foo {
int no_default;
int yes_default = 0;
};
- There is struct inheritance. Use the colon to denote structs with all fields in the parent struct:
struct A { };
struct B : A { }; // Has all A's fields
-
In C++, a struct can have methods, inheritance, etc. just like a C++ class.
- It is possible--get this--to redefine a class/instance method. Instead of using interfaces like normal humans would (hint: they don't exist), you may define a class in the header, then change the definition of the class.
- According to your colleagues,
new Something()
gives you a pointer to something, whereasSomething()
gives you the exact thing. For the case ofstd::string
, this helpful post explains four variants:
1. `std::string s = std::string("foo"); // creates a temporary std::string object containing "foo", then assigns it to s`
2. `std::string s = "foo";` // equivalent to 1. Internally, this runs one of the constructors in std::string that accepts const char*.
3. `std::string s = new std::string("foo"); // compiler error while trying to assign a pointer to a variable of type std::string`
4. `std::string s("foo");`
"One of the main benefits of using std::string is that it manages the underlying string buffer for you automatically, so new-ing it kind of defeats that purpose."
- Function/method names are
UpperCamelCase
, unless they are cheap, (e.g.) "so cheap that you normally wouldn't bother caching its return value when calling it in a loop", in which case they areunderscored_things
; such a function normally consists of only one comparison. do {...} while (0)
is the de facto way of writing a macro that expands correctly, whether in a one-liner if statement, or in an if-else.- Macros are not substituted in macros. (Otherwise
#ifdef
s will get complicated) - Headers can contain other headers, but should not.
- Rule: When addressing compile errors in your programs, always resolve the first error produced first.
- Vectors are just dynamic arrays. A vector comes with convenient functions like
push_back()
andpop_back()
to use a vector as a queue or a stack. - Compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way. Use vector unless you have a very, very small array, and know what you are doing.
- If both a
<foo>
and<foo.h>
exists, then the.h
version is deprecated. Use the non-h version. - When used to get strings,
cin >> a_string
will only get the input up to a space. To get the whole line, usegetline(cin, a_string)
instead. - Anything created with
new
and notdelete
d is automatically leaked. Anything manually allocated withmalloc
and notfree
d is also automatically leaked. - Use
delete
by itself to free a single object. Usedelete []
with square brackets to free a heap array. - Unless you do systems programming, there is almost no reason to pick C over C++. Simply not using the C++ features you don't use is also an option.
- You can't
cout
a string unless you#include <string>
. - Pointers and references are complicated. As such, C++11 provides an additional way to declare yet another kind of reference, called rvalue referneces, using the double-ampersand syntax:
A&&
. - Header files exist so you don't need to recompile a class if the definition didn't change (PDF).
- In a move that could possibly backfire, the C++20 lambda syntax uses square brackets, like
[](auto x, auto y) { /*...*/ };
. - A
struct
's members are public by default. Aclass
's members are private by default. and
is the exact same as&&
.const
is used when you want to pass in an expensive variable by reference (instead of by value, which makes copies; this happens a lot with strings), but you want to ensure the variable is not modified once passed in. Function parameters that do such a thing should be marked withconst
.