Can someone tell me the benefit of header files in C++? I believe there must be good reason for it, but I don't quite understand why. Why would I want to create some code in two seperate files, somewhat repetitive, when I can write it all one time, in one place, and with less code like in so many other languages?
Wouldn't the following be much easier to write, manage, understand, and be more efficient than using a header file and implementation file?
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class MyClass
{
public:
MyClass( ) // constructor
{
msg = "Hello World";
}
void MyMethod( )
{
cout << msg << endl;
}
~MyClass( ) { } // destructor
private:
string msg;
};
int main (void)
{
MyClass test;
test.MyMethod(); // display Hello World
_getch(); // pause before exit
return (0);
}
...instead of doing this, which seems like twice the work:
// MyClass.h
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class MyClass
{
public:
MyClass( ); // constructor
void MyMethod( );
~MyClass( ); // destructor
private:
string msg;
};
// MyClass.cpp
#include "MyClass.h"
MyClass::MyClass()
{
msg = "Hello World";
}
void MyClass::MyMethod()
{
cout << msg << endl;
}
MyClass::~MyClass()
{
// destructor code here
}
int main (void)
{
MyClass test;
test.MyMethod();
_getch(); // pause before exit
return (0);
}
If anyone can point out to me why it would be more advantageous to use header/implementation files instead of creating it in one place, I would really appreciate it. Thanks!!