Classes
Contents
Header Files
Separating the class into ".h" and ".cpp" .In the examples above we have written the "Person" class in a single file. Normally the header file contains the declaration of the class and the ".cpp" file contains the body of the methods. Another file may want to use the class and only needs to include the header file for the class in order to use the class. The header file not contain the body of the code for the functions. The declaration in the header file can be thought of as the declaration for a function with the body of the function defined elsewhere.
There are 3 files: "person.h", "person.cpp" and "main.cpp" .
File: person.h
#ifndef PERSON_H #define PERSON_H #include <string> #include <iostream> using namespace std ; class Person { private: string firstName ; string lastName ; int age ; public: void print() ; void setData( string firstNameP, string lastNameP , int ageP ) ; }; #endif
File: person.cpp
#include "person.h" void Person::setData( string firstNameP, string lastNameP , int ageP ) { firstName = firstNameP ; lastName = lastNameP ; age = ageP ; } void Person::print() { cout << "Name:" << firstName << " " << lastName << " Age: " << age << endl ; }
File: main.cpp
#include <iostream> #include <string> #include "person.h" using namespace std ; int main() { Person person1 ; person1.print() ; Person* personPtr ; personPtr = new Person() ; personPtr->print() ; //personPtr = 0 ; delete personPtr ; return(0) ; }As the above code shows we include the "person.h" and can then use the "Person" class .
Exercise:
1) Create a folder and separate your earlier vehicle class into a vehicle.h , vehicle.cpp and main.cpp.