Class Code And Header Files
Defining member functions outside the class definition
- C++ provides a way to separate the definition portion of the class from the implementation portion.
- This is done by defining the class member functions outside the class definition.
Example
class Date { private: int m_nMonth; int m_nDay; int m_nYear; Date() { } // private default constructor public: Date(int nMonth, int nDay, int nYear) { SetDate(nMonth, nDay, nYear); } void SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; } int GetMonth() { return m_nMonth; } int GetDay() { return m_nDay; } int GetYear() { return m_nYear; } };
Could be rewritten
class Date { private: int m_nMonth; int m_nDay; int m_nYear; Date() { } // private default constructor public: Date(int nMonth, int nDay, int nYear); void SetDate(int nMonth, int nDay, int nYear); int GetMonth() { return m_nMonth; } int GetDay() { return m_nDay; } int GetYear() { return m_nYear; } }; // Date constructor Date::Date(int nMonth, int nDay, int nYear) { SetDate(nMonth, nDay, nYear); } // Date member function void Date::SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; }
Putting class definitions in a header file
- Class definitions can be put in header files in order to facilitate reuse in multiple files.
Example
Date.h
#ifndef DATE_H #define DATE_H class Date { private: int m_nMonth; int m_nDay; int m_nYear; Date() { } // private default constructor public: Date(int nMonth, int nDay, int nYear); void SetDate(int nMonth, int nDay, int nYear); int GetMonth() { return m_nMonth; } int GetDay() { return m_nDay; } int GetYear() { return m_nYear; } }; #endif
Date.cpp
#include "Date.h" // Date constructor Date::Date(int nMonth, int nDay, int nYear) { SetDate(nMonth, nDay, nYear); } // Date member function void Date::SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; }
Now any other header or code file that wants to use the date class can simply #include "Date.h"