I am new to OOP in C++. I have a class that doesn't need to run any code neither does it need any parameter when the object is created, should I still write a constructor only for the initialization of the variables.
I can do this:
#include <iostream> class Something { private: const char* msg = "Hewwo World"; // i can initialise here public: void Print() { for (int i = 0; i < 11; ++i) { std::cout << *msg++; } } }; int main() { Something smth; smth.Print(); } instead of this:
#include <iostream> class Something { private: const char* msg; public: Something() { msg = "Hewwo World"; } void Print() { for (int i = 0; i < 11; ++i) { std::cout << *msg++; } } }; int main() { Something smth; smth.Print(); } both give the same output and the first method is a lot cleaner (according to me). Is there any reason why I should use the second method?
Something() : msg("Hewwo World") {}. That makes the example equivalent to the first (apart from the fact that the constructor is generated by the compiler in the first case, and the programmer in the second). Rough rule of thumb - if you can achieve the same net effect using a member initialiser versus a subsequent assignment in the constructor body, prefer to use the initialiser.