Tip #1:
Whenever a .h
or a .cpp
have external references, the header of this external reference should be included. This increases decoupling between modules and improves code readability.
References:
- Softwareengineering: https://softwareengineering.stackexchange.com/questions/262019/is-it-good-practice-to-rely-on-headers-being-included-transitively
Tip #2:
Always use the reserved word void
in methods/functions that do not receive parameters, for example replace T::foobar()
for T::foobar(void)
is an excellent practice because:
Improves readability: T::foobar()
looks like a call
while T::foobar(void)
looks like an implementation and/or
definition);
Improves the interpretation of the code by the compiler, avoiding a
problem called Most vexing parse;
Ensures compatibility with C
, for in C
to
functions declared as foobar()
do not have the same meaning
which functions declared as foobar(void)
.
References:
Wikipedia: https://en.wikipedia.org/wiki/Most_vexing_parse
Stackoverflow: https://stackoverflow.com/questions/51032/is-there-a-difference-between-foovoid-and-foo-in-c-or-c
Tip #3:
Always use virtual destructors in class settings is another good practice, this allows polymorphic manipulations, allows cascatear
the call of the destructors of the derived class to the base classes, avoiding Leaks from memory.
References:
- Stackoverflow: https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors
Tip #4:
Class builders allow you to boot your members into a boot list, this was done to be used! Avoid initializing your class members within the constructor implementation.
References:
Stackoverflow: https://stackoverflow.com/questions/33683010/best-practice-for-class-member-initialization
Stackoverflow: https://stackoverflow.com/questions/12927169/how-can-i-initialize-c-object-member-variables-in-the-constructor
What your code would look like:
main.cpp
#include "Teste_1.h"
int main(void){
Teste_1 * test = new Teste_1( "you never win! but you can get my money", "Hello" );
delete test;
return 0;
}
Test_1.h:
#ifndef TESTE_1_H_INCLUDED
#define TESTE_1_H_INCLUDED
#include <string>
class Teste_1{
private:
std::string var_str1;
std::string var_str2;
public:
Teste_1( std::string var1, std::string var2 );
virtual ~Teste_1(void);
};
#endif // TESTE_1_H_INCLUDED
Teste_1.cpp
#include "Teste_1.h"
#include <string>
Teste_1::Teste_1( std::string var1, std::string var2 ) :
var_str1(var1),
var_str2(var2)
{
}
Teste_1::~Teste_1(void){
}
Compiling:
$ g++ main.cpp Teste_1.cpp -o teste
Continues with the error: main.cpp|4|Undefined Reference to `Teste_1::Teste_1(Std::__cxx11::basic_string<char, Std::char_traits<char>, Std::allocator<char> >, Std::__cxx11::basic_string<char, Std:char_traits<char>, Std:::allocator<char> >)'|
– user83187