Trickier C++ Stuff
- Constructor Intricacies
What the constructor does
First, any base class constructors are executed.
Then, each data member in the class is constructed next, in the order of declaration in the class (not in the order of appearance in the constructor initializer list). Finally, the constructor body is executed.
- Assignment Operator
-
Always check for self-assignment
If not and your class contains dynamically allocated memory, you will delete that memory and wreak havoc.
The assignment operator does not chain!
Note: this is only true if you define an assignment operator in a derived class. If you don't define one and use the compiler-generated ones, they will chain. But if anywhere in the inheritance chain you have defined your own operator=, this will break the chain. This is confusing because it kind of looks like a copy constructor, which does chain. In derived class assignment operators, you have to explicitly call down (or up) to the base class assignment operator. Like
Derived& operator=(const Derived& rhs) { if(&rhs == this) return *this; Base::operator=(rhs); ...<do Derived assignment stuff>... }
- Liskov Substitution Principle
This says that anywhwere a class Base can be used, a class Derived from Base can be substitued in without any problems. So say you have some functions that operate on a Base&, you should be able to pass in a Dreived& and have things still work.