header files c++ code example
Example 1: what is a header in c++
// my_class.h
namespace N
{
class my_class
{
public:
void do_something();
};
}
Example 2: c++ header files
// You should use header files when you wan't to split your
// program across multiple files. Use it like this:
// vec2.hpp
class vec2 {
public:
void printVec(); // Decleration
float x, y;
}
// vec2.cpp
void vec2::printVec() { // Implementation
std::cout << x << y << std::endl;
}
Example 3: what is a header in c++
// sample.h
namespace N // namespace declaration
{
inline namespace P
{
//...
}
enum class colors : short { red, blue, purple, azure };
const double PI = 3.14; // const and constexpr definitions
constexpr int MeaningOfLife{ 42 };
constexpr int get_meaning()
{
static_assert(MeaningOfLife == 42, "unexpected!"); // static_assert
return MeaningOfLife;
}
using vstr = std::vector<int>; // type alias
extern double d; // extern variable
void print_to_log();
class my_class // regular class definition,
{ // but no non-inline function definitions
friend class other_class;
public:
void do_something(); // definition in my_class.cpp
inline void put_value(int i) { vals.push_back(i); } // inline OK
private:
vstr vals;
int i;
};
struct RGB
{
short r{ 0 }; // member initialization
short g{ 0 };
short b{ 0 };
};
template <typename T> // template definition
class value_store
{
public:
value_store<T>() = default;
void write_value(T val)
{
//... function definition OK in template
}
private:
std::vector<T> vals;
};
template <typename T> // template declaration
class value_widget;
}
Example 4: what is a header in c++
// my_class.cpp
using namespace N;
using namespace std;
void my_class::do_something()
{
cout << "Doing something!" << endl;
}
Example 5: what is a header in c++
int x; // declaration
x = 42; // use x
Example 6: what is a header in c++
// my_class.h
namespace N
{
class my_class
{
public:
void do_something();
};
}