\( % theorem \newenvironment{pf}{\textbf{Proof.}}{\rule{1ex}{1ex}} \newtheorem{qu}{Question} \newtheorem{thm}{Theorem} \newtheorem{rmk}{Remark} \newtheorem{go}{Goal} \newtheorem{df}{Definition} \newtheorem{prop}{Proposition} \newtheorem{mot}{Motivation} \newtheorem{ex}{Example} \lstnewenvironment{code}{}{} \newcommand{\nc}{\newcommand} %% env \nc{\env}[2]{ \begin{#1} #2 \end{#1} } \nc{\arr}[2]{ \begin{array}{#1} #2 \end{array} } \nc{\arrb}[2]{ \left\{ \begin{array}{#1} #2 \end{array} \right. } \nc{FTC}[3]{ \left[#3\right]^{#2}_{#1} } \nc{\bracs}[1]{ \left[#1\right] } \nc{\brac}[1]{ \left(#1\right) } \nc{\bracp}[1]{ \left\{#1\right\} } \nc{\intd}[4]{\int^{#2}_{#1}\left(#3\right) #4} % shortcut \nc{\Lra}{\Leftrightarrow} \nc{\Ra}{\Rightarrow} \nc{\La}{\Leftarrow} \nc{\C}{\mathbb{C}} \nc{\R}{\mathbb{R}} \nc{\Fc}{\mathcal{C}} \nc{\bds}{\boldsymbol} \nc{\ds}{\displaystyle} % begin end \nc{\bit}{\begin{itemize}} \nc{\eit}{\end{itemize}} \nc{\bcode}{\begin{code}} \nc{\ecode}{\end{code}} \nc{\bsage}{\begin{sageblock}} \nc{\esage}{\end{sageblock}} %pic \nc{\pic}{\includegraphics} \nc{\svg}{\includesvg} \nc{\pica}{\includegraphics[width=100px,height=100px]} \nc{\picb}{\includegraphics[width=150px,height=150px]} \nc{\vs}{\vspace} \nc{\tbf}{\textbf} %arrow \nc{\upa}{\nearrow} \nc{\downa}{\searrow} \nc{\upw}{\rcurvearrowright} \nc{\downw}{\curvearrowright} \)

Ch 9 Class, etc

Representation vs Operation

  • Representation: How to represent the data in an object

  • Operation: What operations can be applied to object


State : current value (Mutable)


User defined types

  • class

  • enumeration

Example of class

class X{
    public:
        int m; //data member
        int mf(int v){ //function member
            int old=m;m=v;return old;
        }
}; // Do not forget semi colon!

How to use

X var;
var.m=7;
int x=var.mf(9);// what is x?

[9.3] Interface and implementation

interface

class X{ 
    private: //private members (only for class member)
    //functions    
    // types
    public: //public members 
    //functions    
    // types
};

A user cannot directly refer to a private number.

Private is default!

class X{
    int a;
};

means

class X{
    private:
        int a;
};
```c++
So
```c++
X x;
x.a=1;

gives an error. How can I access a?

Example

We have to go through a public function to access private members.

class X{
    private:
    int a;
    public:
    int set(int b){a=b;}
    int get(){return a;}
}

So

X x;
x.set(1);
cout<<x.get(); //print 1

struct

struct X{
    int a;
};

means

struct X{
    public:
        int a;
};

Comment on c version

C version struct does not include member functions.

[9.4] Evolving a class

struct Date{
    int y;
    int m;
    int d;
};
Date today;

To setup an object, today,

today.y=2016;
today.m=2;
today.s=11;

A problem

Date x;
x.m=13;
x.d=32;

Does it makes sense? How about leap year?

Solution 1: Helper function

// We only check year and month.
#include <stdexcept>
void init_day(Date & dd, int y,int m,int d){
    if(  0< m && m <= 12){
        dd.y=y;
        dd.m=m;
        dd.d=d;    
    } 
    else throw invalid_argument("invalid date!");
}

Ok! But we want to put in Date class. (You cannot use it if y,m,d are private.)

[9.4.4] Solution 2: member function

class Date{
    public:
        Date(int y, int m, int d);//Constructor!
    private:
        int y,m,d;
};

Let us define a Date member function. Actually, it is called a constructor!

Date::Date(int yy,int mm, int dd) //class::member-function
    :y{yy}, m{mm}, d{dd}{}   //c++11: member initializer list

inline

We can also define within class as an inline function.

class Date{
    public:
        Date(int yy, int mm, int dd):y{yy}, m{mm}, d{dd}{}
    private:
        int y,m,d;
};

The compiler will try to generate code for the function at each point of call.

Assignment

class Date{
    public:
        Date(int yy, int mm, int dd){y=yy,m=mm,d=dd;}
    private:
        int y,m,d;
};

Declare and assign later.

const case

We assgined xx later.

How to fix

struct X{
    const int x;
    X(int xx):x{xx}{}// OK   
};

How to declare?

Date today {2016,2,11};// OK
Date tomorrow; //Error

Why? (No more default Constructor!)

Delegating Constructors

Date::Date(): Date(0,1,1){}//C++11

Of course, we need to declare Date() first.

class Date{
    public:
        Date(int y,int m,int d);
        Date();// Declare!
    private:
        int y,m,d;
};

initialize members.(c++11)

class Date{
    public:
        Date(int yy,int mm,int dd):y{yy},m{mm},d{dd}{}
        Date(){}
    private:
        int y=0,m=1,d=1;
};

More member functions

class Date{
    public:
        Date(int yy,int mm,int dd):y{yy},m{mm},d{dd}{}
        Date():Date(0,1,1){}
        int month(){return m;}
    private:
        int y,m,d;
};
void f(Date d1, Date d2){
    cout<<d1.month()<<" "<<d2.month()<<endl;
}

Check up! -20 mins

Make a function print which prints Date.

void print(Date d1);

and

Date d1 {2016,2,11};
print(d1);
// Feb-11, 2016

You need to make extra member functions

int day();
int year();

[9.4.6] Reporting errors

class Date{
    public:
        class Invalid{};// A class as exception
        Date(int y, int m,int d);
        Date():Date(0,1,1){}
        int year(){return y;}
        int month(){return m;}
        int day(){return d;}
    private:
        int y, m, d;
        bool is_valid();
};
Date::Date(int yy,int mm,int dd):y{yy},m{mm},d{dd}
{
    if(!is_valid()) throw Invalid{};
}
bool Date::is_valid(){
    if(m<1||m>12) return false;
    // skip other checkings.
    else return true;
}
void f(int m){
    try{
        Date date {2014,m,2};
    }
    catch(Date::Invalid){
        throw invalid_argument("invalid date");
    }
}

check up. Make a Student class which have

  • private : string last, string first,double GPA
  • get_name() retruns last, first as a string
  • get_GPA() returns GPA

  • 0 < = GPA < = 4.0 If not, throw an invalid_argument exception

  • Check string concaternation.
int main(){
    try{
        Student taylor {"Taylor","Swift",3.3};
        cout<<taylor.get_name()<<endl; // Swift, Talyor
        cout<<"GPA="<<taylor.get_GPA()<<endl;
        Student john {"John","Doe", -2.1};
        cout<<john.get_name()<<endl;
        cout<<"GPA="<<john.get_GPA()<<endl;
    }
    catch(exception & e){
        cout<<e.what()<<endl;
    }
}