0

Hello i have a code like this in c++:

#include <iostream>

using namespace std;

namespace exercises
{

class String;
ostream& operator<<(ostream&, const String&);
istream& operator>>(istream&, String&);

class String
{
public:
    explicit String(const char* str_="");
    ~String();

    String(String const &oStr_);    

    String& operator=(const String& oStr_);
    String& operator=(const char* oStr_);

    bool operator==(const String& oStr_)const;
    bool operator<(const String& oStr_)const;
    bool operator>(const String& oStr_)const;   

    char operator[](std::size_t)const;
    char& operator[](std::size_t);  

    const std::size_t Len()const;   
    const char* CStr()const;

private:
    char* m_str;
};

}

but i don't know one thing. i can set all functions (with source) inside this code header file and it's work completely so why people use .lib file when they can set all the sources inside the header file and just include the header file and enjoy it ? i know one thing : header file is for declaration and .cpp is for sources because if you set source inside the header file you maybe get some undefined error (but i didn't) so is it important for me to set my soruces in cpp file or just i can use header file for sources?

myOwnWays
  • 59
  • 4
  • Note that when you see function implementations in header files it's often because you're actually looking at a `template` instead of an actual type or function definition. `template`s are special in that the consumer needs their definitions, not just their declarations. – Dai Aug 06 '17 at 04:57
  • a .lib file has been run through the compiler already and doesn't need to be compiled again when you link to it. a .lib in windows is similar to a .a or .o file on other platforms. – xaxxon Aug 06 '17 at 04:57
  • Why don't you place headers in source instead ? '-' (That's just a question, I don't think any of the two are agreat idea.) – Alceste_ Aug 06 '17 at 04:57

1 Answers1

0

You cannot define of the same functions/classes multiple times, so it might be that it does not give you a compile error because you only include the header once, but if you will include it again in another header it will give you an error that your classes/functions are already defined. Templated classes or functions have to be defined in the header and the compiler will run through a proccess where it fills in all the used template arguments.

Andreas Loanjoe
  • 2,205
  • 10
  • 26