CHAP 4 : C++ - CLASS AND OBJECT 
CLASS     class <class-name>
    {
        private :
                    <variable declarations>
                    <function declarations>
        public :
                    <variable declarations>
                    <function declarations>
    };

Access Specification

Class Implementation             #include <iostream.h>
            // a class Test with a constructor function
            class Test {
                public :                // 'public' function
                    Test();             // the constructor
            }

            Test::Test() {
                cout << " constructor of class Test called<<endl;
            }

            // and here is the test program :
            Test g;                    // global object
            void func() {
                Test                    // local object
                    I;                    // in function func()
                cout << "here's function func() " << endl;
            }

            int main() {
                Test  x;               // local object in function main()
                cout << " main() function" << endl;
                func();
                return 0;
            }

Constructor & Destructor

Object's lifetime

Constructor Destructor ex2 :

    // class definition
    class Person {
        public :
            Person();                            // constructor
            ~Person();                          // destructor
 
            // function to set fields
            void setname(char const *n);
            void setaddress(char const *a);
            void setphone(char const *p);

            // function to inspect fields
            char const *getname() const;
            char const *getaddress() const;
            char const *getphone() const;

        private :
            char *name;                        // name of person
            char *address;                    // address field
            char *phone;                       // telephone number
     }

    //constructor
    Person :: Person() {
        name = 0;
        address = 0;
        phone = 0
    }

    //destructor
    Person :: ~Person() {
        free(name);
        free(address);
        free(phone);
    }
 

Constructor with arguments

            Person :: Person(char const *n, char const *a, char const *p){
                name = xstrdup(n);
                address = xstrdup(a);
                phone = xstrdup(p);
            }             class Person {
                public:
                        Person(char const *n, char const *a, char const *p);
                        ...................
            }
 
 
 

Constructor with default argument

            class Adder {
                int a, b, x;
                public:
                    Adder( int P=10, int Q=5) {
                        a= Q;
                        b= P;
                        x= a + b;
                    }
                    void result(void){
                        cout << " Result = " << x <<endl;
                    }
            }

            void main() {
                Adder A;                        // use the default value
                A.result();
                Adder B(2,1);                 // use the parameter value
                B.result();
                Adder C(7);                    // use the parameter for the
                C.result();                        // first data in the list
            }
 
 

OBJECT

Assigning Objects

            //simple Date class
            class Date {
                public :
                    Date( int =1, int = 1, int = 1990 )              // default constructor
                    void print();
                private :
                    int month;
                    int day;
                    int year;
            }

            // simple Date constructor with no range checking
            Date :: Date( int m, int d, int y ){
                month = m;
                day = d;
                year = y;
            }

            // Print the Date in the form mm-dd-yyyy
            void Date :: print(){
                cout << month << '-' << day << '-' << year;
            }

            main() {
                Date d1(7, 4, 1993), d2;    // d2 defaults to 1/1/1990
                cout << "d1=";
                d1.print();
                cout << "\nd2 = ";
                d2.print();
                d2 = d1;                            // assignment by memberwise copy
                cout << "\n\nAfter default memberwise copy, d2= ";
                d2.print();
                cout << endl;
                return 0;
            }
 

Passing objects to functions

            #include <iostream.h>
            class samp{
                int i;
            public:
                samp( int n ) { i=n }
                int get_i() { return i; }

                // return suare of o.i
                int sqr_it (samp o){
                    return o.get_i() * o.get_i();
                }
 
            main() {
                samp a(10), b(2);
                cout << sqr_it(a) << "\n";
                cout << sqr_it(b) << "\n";
                return 0;
            }

            class samp {
                int i;
                public :
                    samp (int n) { i=n; }
                    void set_i (int n) { i=n; }
                    int get_i() { return i; }
            }

            /* set o.i to its square. This has no effect on the object used to call sqr_it() */
            void sqr_it(samp o) {
                o.set_i(o.get_i() * o.get_i());
                cout << "copy of a has i value of " << o.get_i() << "\n";
            }

            main() {
                samp a(10);
                sqr_it (a);                                                     // a passed by value
                cout << " But, a.i is unchanged in main = ";
                cout << a.get_i();                                         // display 10
                return 0;
            }

            class samp {
                int i;
                public:
                    samp (int n){
                        i = n;
                        cout << "constructing \n";
                    }
                    ~samp(){
                        cout << "destructing \n";
                    }
            }

            // return square of o.i
            int sqr_it (samp o) {
                return o.get_i() * o.get_i();
            }

            main() {
                samp a(10);
                cout << sqr_it(a) << "\n";
                return 0;
            }

            #include <iostream.h>
            class time {
                int hours,minutes;
                public :
                    void gettime(int h, int m){
                        hours = h;
                        minutes = m;
                    }
                    void puttime(void){
                        cout << hours << "hours and ";
                        cout << minutes << "minutes " << "\n";
                    }
                    void sum(time, time);                    // objects are arguments
            };

            void time :: sum( time t1, time t2) {        // t1, t2 are objects
                minutes = t1.minutes + t2.minutes;
                hours = minutes/60;
                minutes = minutes % 60;
                hours = hours + t1.hours + t2.hours;
            }

            main() {
                time T1, T2, T3;
                T1.gettime(2, 45);
                T2.gettime(3, 30);
                T3.sum(T1, T2);
                cout << " T1 = "; T1.puttime();                // display T1
                cout << " T2 = "; T2.puttime();                // display T2
                cout << " T3 = "; T3.puttime();                // display T3
            }

Returning objects             #include <iostream.h>
            class complex {                                  // x + y form
                float x, y;
                public:
                    void input (float real, float imag){
                        x = real; y = imag;
                    }
                    friend complex sum(complex, complex);
                    void show(complex);
            }

            comple sum(complex c1, complex c2){
                complex c3;                                    // objects c3 is created
                c3.x = c1.x + c2.x;
                c3.y = c1.y + c2.y;                         // returns object c3
            }

            main() {
                complex A, B, C;
                A.input(3.1, 5.65);
                B.input(2.95, 1.2);
                C = sum(A,B);                                // C = A + B
                cout << " A = "; A.show(A);
                cout << " B = ";  B.show(B);
                cout << " C = "; C.show(C);
            }

Friend function & friend classes

            class ABC {
                ..........
                public :
                    ...........
                    friend void xyz(void);                        // declaration
            };
 
 
 
 
              #include <iostream.h>
            class sample{
                int a, b;
                public:
                    void setvalue(){
                        a = 25; b = 40;
                    };
                    friend float mean( sample s );              // FRIEND declared
            }

            float mean(sample s){
               return float(s.a + s.b)/2.0;
            }
 
            main() {
                sample x;                                                // object x
                x.setvalue();
                cout << " mean value = " << mean(x) << "\n";
            }
 

            class X {
                .............
                int func1();                                    // member function of X
                .............
            };
            class Y {
                ............
                friend int X :: func1();                    // func1() of X is friend of Y
                ............
            };             class Z{
                ...........
                friend class X;                            // all member function of X are friends to Z
            }             #include <iostream.h>
            class ABC;                                    // forward declaration
            class XYZ{
                int x;
                public:
                    void setvalue(int i){ x = i;}
                    friend void max (XYZ, ABC);
            };

            void max( XYZ m, ABC n ){           // Definition of friend
                if (m.x >= n.a) cout << m.x;
                else cout << n.a;
            }

            main() {
                ABC abc;
                abc.setvalue(10);
                XYZ xyz;
                xyz.setvalue(20);
                max(xyz, abc);
            }

                class ABC;
 

Latihan:

1. Dapatkan output bagi keratan aturcara dibawah:

    // friend can access private members of a class
    #include <iostream.h>
    // modified count class
    class count {
        friend void setX(count &, int);                // friend declaration
            public:
                count() { x = 0; }                           // constructor
                void print() const {
                    cout << x << endl;                     // output
                }
            private:
                int x;                                              // data member
        };
 
        // can modify private data of count because
        // set x is declared as a friend function of count
        void setx(count &c, int val) {
            c.x = val;                                            // legal: setx is a friend of count
        }

        main() {
            count object;
            cout << " object.x after instantiation : ";
            object.print();
            cout << " object.x after call to setx friend function : ";
            setx(object, 8);                                    // set x with a friend
            object.print();
            return 0;
        }

2. Cari kesalahan aturcara di bawah :

    #include <iostream.h>
    //modified count class
    class count {
        public:
            count(){ x = 0;}                                        // constructor
            void print() const { cout << x << endl;}    // output
        private:
            int x;                                                         // data member
    }

    // function tries to modify private data of count,
    // but cannot because it is not a friend of count
    void cannotsetx( count &c, int val){
        c.x = val;                                                     // 'count :: x' is not accessible
    }

    main() {
        count object;
        cannotsetx( object, 3);                                // cannotsetx is not a friend
        return 0;
    }

ASSIGNMENT 2
 

  1. Bina satu kelas Jurujual yang mempunyai tatasusunan 12 bulan jualan yang dinilaiawalan ( initialization) sebagai sifar dengan menggunakan constructor dan satu fungsi SetJurujual yang merupakan jumlah jualan yang dibekalkan oleh pengguna untuk sebulan. CetakJualanTahunan merupakan satu fungsi public yang mencetak jumlah jualan untuk 12 bulan terakhir. Fungsi JumlahJualanTahunan akan menjumlahkan jualan selama 12 bulan dan fungsi ini dipanggil ketika CetakJualanTahunan dan ditakrifkan didalam private. CetakJualanTahunan akan menukarkan jumlah jualan ke format dollar. Fungsi main akan membina satu objek s untuk mendapatkan JumlahJualanDariPengguna (fungsi ini ditakrifkan dalam public ) dan mencetak jualan tahunan penjual dengan tiada struktur kawalan. Buat file definition bagi Jurujual, implementation file untuk pelaksanaan setiap fungsi yang ditakrifkan dalam kelas Jurujual dan satu program file lain untuk memanggil fungsi JumlahJualanDariPengguna dan CetakJualanTahunan.
  2. Buat aturcara yang lengkap dengan file definition, implementation file dan satu driven test file bagi tujuan menukarkan data masa kepada masa tentera(military time) dan masa biasa (standard time) berdasarkan soalan-soalan berikut :
Tugasan ini hendaklah dihantar selewat-lewatnya pada 8/1/99. Tugasan anda tidak akan dilayan selepas tarikh tersebut