...
Code Block |
---|
|
class ExampleClass {
public:
private:
// Member variables should always be private. If you need access to them, provide getters and setters.
int hello_there;
const double kGeneralKenobi;
static int _its_over_anakin;
};
// Remember static variables must be redeclared outside of the class declaration
int ExampleClass::_its_over_anakin {0}; |
...
We prefer to use initializer lists when initializing member variables, however there are cases where we should stick to initializing member variables within the constructor.
Code Block |
---|
|
class ExampleClass {
public:
ExampleClass();
ExampleClass(int num_apple_pies);
private:
int apple_pies, banana_pies;
double slices_left;
}
ExampleClass::ExampleClass() : apple_pie {0}, banana_pies {0}, slices_left {0.0f} {}
// You can stack your initializing list. Just make sure they start in the same column
ExampleClass::ExampleClass(int num_apple_pies) : apple_pies {num_apple_pies},
banana_pies {0} {
slices_left = 6 * num_apple_pies; // If an operation is required, preferred if initialization is within constructor
} |
...
When statically declaring a struct, you should initialize it immediately. If a default constructor exists, call that, else call another constructor.
Code Block |
---|
|
class ExampleClass {
public:
ExampleClass();
ExampleClass(int num_apple_pies);
private:
int apple_pies, banana_pies;
double slices_left;
}
int main() {
ExampleClass default_class {}; // Preferred over `ExampleClass class_with_apples()`
ExampleClass class_with_apples {1}; // Preferred over `ExampleClass class_with_apples(1)`
} |
If declaring a class pointer, initialize to nullptr
if no other options exist:
Code Block |
---|
|
class ExampleClass {
...
};
int main() {
ExampleClass * example_pointer = nullptr; // Good!
ExampleClass statically_declared_class {};
ExampleClass * other_pointer = &statically_declared_class; // Also good!
ExampleClass * one_more_pointer = functionThatReturnsAClassPointer(); // Good too!
} |
...