Zebra0

Learn to Program Step-by-Step

We will start our discussion of classes by using a class first.

To match this example, create a folder called cpp on the C: drive, and then create a sub-folder in cpp called classes. This will give you a directory structure called C:/cpp/classes

Download Date.cpp and save it as Date.cpp to the folder you created (C:/cpp/classes), by selecting File, Save page as. (Make sure you remove the .txt extension.)

Download Date.h and save it as Date.h to the folder you created, by selecting File, Save page as. (Make sure you remove the .txt extension.)

In your C++ compiler, write the program shown below:

1
2
3
4
5
6
7
8
9
#include "c:/cpp/classes/Date.cpp"
#include <iostream>
using namespace std;
int main() {
   Date today;
   cout<<today<<endl;
   system("pause");
   return 0;
}
CODE

On the Mac using XCode, use this code:

1
2
3
4
5
6
7
8
9
#include "/Users/yourname/Documents/mycppDate.cpp"
#include <iostream>
using namespace std;
int main() {
   Date today;
   cout<<today<<endl;
   system("pause");
   return 0;
}
CODE

Code for Mac using XCOde

Read this if you are using Microsoft Visual Studio and have a problem getting the program to compile.

I am running g++ 4.8.5 on RHEL

Explanation:

  • We have included the Date.cpp file that defines the Date class. It includes the Date.h file
  • The Date.h file shows the function prototype for each method in the class.
  • The Date.cpp file has the function definition for each of these methods.
  • In main, we declare today as an instance of the Date class.
  • Since we do not include any arguments to today, it is given values for the current date.
  • Classes usually have a method to print to an output stream so that we can print them or write to a file.
  • This program will display todays date as 12/12/2017.

It is very important that you get this working.
We will be using the Date class in several more examples.
As you do each of the examples, look at the code in these two files
to see how the methods are implemented.

Here is another example: You may need to include stdafx on your system:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx"
#include "c:/cpp/classes/Date.cpp"
#include <iostream>
using namespace std;

int main()
{
  Date today;
  cout << today << endl;
  system("pause");

  Date darwinBirthday(2,12,1809);
  cout << darwinBirthday << endl;
  system("pause");

  Date lincolnBirthday("2/12/1809");
  cout << darwinBirthday << endl;
  system("pause");

  return 0;
}//main
CODE
Like us on Facebook:


OER: Open Educational Resource
Creative Commons License Author: Janet E. Joy; Publisher: Zebra0.com
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
Creative Commons Attribution-NonCommercial 4.0 International License
Last modified: September 13 2017 14:42:57.