Date Class - Tirgul

#include <iostream>
#include <stdio.h>
#include "Date.h"

using namespace std;

int main() {
// defining a Data Object
    Date HerBirthDay(19,8,1976);
    printf("Her birthday is on %d / %d / %d \n",
           HerBirthDay.theDay( ) , HerBirthDay.theMonth( ),
           HerBirthDay.theYear( ) );
    HerBirthDay.advance( );
    printf("On %d / %d / %d she'll be very happy\n",
           HerBirthDay.theDay( ) , HerBirthDay.theMonth( ),
           HerBirthDay.theYear( ) );
// HerBirthDay.day_ ++ ; // illegal: day_ is private
// HerBirthDay.month_=8;// illegal: month_ is private
    return 0;
}

Function Prototype- הצהרה

We can see the our Date.h only contains prototypes of our class.

Const member function

Here we also notice that the functions above end with const. const ensures us that the functions will not change the object but rather read only its values

Implementing our Class

In Date.cpp we implemented our member funtion.

We use the :: or scope resolution operator to Define funtions in our class.

Constuctors

  1. doesnt return (not even void)

  2. its name is similar to classes

  3. better to initinize with init lists

Public & Private

theDay() is public which mean anyone can call and access it. While day_ is private which means only our class can access (or call when needed). Friend classes/methods can also access or call or private member functions or variables.

Member variables are almost always private

Overloading

If if were to replace our main with the following would the code compile?

NO!!! We don't have a default constructor. We overloaded it.

Lets add a default ctor

The compiler knows which to ctor to call by the number of arguments in the parameter and their types.

Watch out from this!

The following is incorrect

The compiler believes this is a declaration of a function who returns a Date.

Overloading our advance funcion

TABS

Date.h

Default args

We can change

to this

We can only give default args to the end of our functions/ctors so the following is incorrect:

Const

newYear99.advance() can't be called because

isn't a const function but newYear99.theDay() may be called for it is a const function.

Pointer to a const

A pointer to a const can change itself to another address to the following is legal:

But it can't change the value to what it points to so this is illegal

const const

Here cpoint address can't be changed but the values can. While ccpoint can't change either

Const and functions

The following case is illegal

Return values from functions

Here the returned pointer is const, though the original field wasn't. The following is legal:

Here the following is illegal

Last updated