C++ Programming Languages Lecturer:

Omid Jafarinezhad

Fall 2013 Lecture 4

Department of Computer Engineering

1

Outline • object-oriented programming – Classes and class members – Access functions and encapsulation – Constructors and Destructors – Class code and header files – Operator overloading – Composition – Inheritance – Virtual Functions – Template classes – Exceptions 2

Classes and class members struct DateStruct { int nMonth; int nDay; int nYear; }; // Here is a function to initialize a date void SetDate(DateStruct &sDate, int nMonth, int nDay, int nYear) { sDate.nMonth = nMonth; sDate.nDay = nDay; sDate.nYear = nYear; } // … In main … DateStruct sToday; // Initialize it manually sToday.nMonth = 10; sToday.nDay = 14; sToday.nYear = 2040; SetDate(sToday, 10, 14, 2020);

3

Classes and class members struct DateStruct { int nMonth; int nDay; int nYear; };

class Date { public: int m_nMonth; int m_nDay; int m_nYear; }; Date cToday; // declare a Object of class Date // Assign values to our members using the member selector operator (.) cToday.m_nMonth = 10; cToday.m_nDay = 14; cToday.m_nYear = 2020; 4

Classes and class members struct DateStruct { int nMonth; int nDay; int nYear; }; // Here is a function to initialize a date void SetDate(DateStruct &sDate, int nMonth, int nDay, int nYear) { sDate.nMonth = nMonth; sDate.nDay = nDay; sDate.nYear = nYear; }

DateStruct sToday; SetDate(sToday, 10, 14, 2020);

class Date { public: int m_nMonth; int m_nDay; int m_nYear; // Member function void SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; } }; Date cToday; // call SetDate() on cToday cToday.SetDate(10, 14, 2020); 5

Classes and class members #include class Employee { public: char m_strName[25]; int m_nID; double m_dWage;

Employee cAlex; cAlex.SetInfo("Alex", 1, 25.00); Employee cJoe; cJoe.SetInfo("Joe", 2, 22.25); cAlex.Print(); cJoe.Print();

// Set the employee information void SetInfo(char *strName, int nID, double dWage) { strncpy(m_strName, strName, 25); m_nID = nID; m_dWage = dWage; } // Print employee information to the screen void Print() { using namespace std; cout