SlideShare a Scribd company logo
Lecture 09

    Classes and Objects


Learn about:
i) More info on member access specifiers
ii) Constant Objects and Functions
iii) Array of Objects
iv) Objects as Function Arguments
v) Returning Objects from Functions

                                  1/27
Access Specifiers
• What is access specifier?
  – It is the one which specifies which member can be accessed at
    which place.
  – Types of access specifiers :                Data Hiding
      • There are three namely,
                                           ob1                  ob2
           – Private
                                                 Friend Ob
           – Public
              » A class's public members can be accessed by any
                function in a program. Used as an interface of the class -
                Other objects can use it .
           – Protected.                              2/27
Member access specifiers (page164-176)



Kitty     friend of Kitty     Snoopy

public                        public
                  public

private                        private
                   private




                             3/27
How to access the members ?
• If the data members of the class is
  – Private :
     • Cannot access directly outside the class
     • How to access ?
        – We should use member functions to access it.
        – EG : data member ----> int a;
           » int main( )
           » { object name.member function( argument ) }
  – Public :
     • can access outside the class
     • EG : object name . Datamembername = value;
            » ob1.a = 9;                   4/27
                                     Example - Next slide
A Simple Class

#include <iostream.h>
class Student    // class declaration
{                       can only be accessed within class
  private:
    int idNum;          //class data members
    double gpa;
                       accessible from outside and within class
  public:
    void setData(int id, double result)
    { idNum = id;
      gpa = result; }

     void showData()
       { cout << ”Student Id is ” << idNum << endl;
         cout << ”GPA is " << gpa << endl; }
};                                           5/27
A simple program example

#include <iostream.h>                      void main()
                                           {
class Student                                Student s1, s2, s3;
{
                                             s1.setData(10016666, 3.14);
  public:
                                             s2.setData(10011776, 3.55);
   int idNum;
   double gpa;
                                               s3.idNum = 10011886;
     void setData(int, double);                s3.gpa = 3.22;
      void showData();
};                                             :
                                           :
                                                    Okay, because idNum
                                           }        and gpa are public.

//Implementation - refer to notes page 1
(Lecture 9).                                                6/27
A simple program example

#include <iostream.h>                      void main()
                                           {
class Student                                Student s1, s2, s3;
{
                                             s1.setData(10016666, 3.14);
  private:
                                             s2.setData(10011776, 3.55);
   int idNum;
   double gpa;
                                               s3.idNum = 10011886;
 public:                                       s3.gpa = 3.22;
   void setData(int, double);
    void showData();                           :
};                                         :
                                                    Error!!! idNum
                                           }        and gpa are private.


//Implementation - refer to notes page 1                    7/27
(Lecture 9).
Another program example
class student {
    private:
    char sid[20]; char name[20]; int semester;
    int year; float marks[4]; float average;
   public:
// …

     student (char [], char [], int sem =1 , int yr = 1);
     void print( ) ;
     void compute_average( )
       { average = (marks[0]+ marks[1]+ marks[2]+
     marks[3])/4; }
};                                                 8/27
Another program example


// class function members implementation
                                                   default arguments

student :: student (char id[20], char nama[20], int sem =1 , int yr = 1 )
 { strcpy (name, nama); strcpy (sid, id);
    year = yr; semester = sem;
  }

void student :: print ( )
{ cout << “Student Id:”<<sid<<endl;
  cout << “Student Name:”<<name<<endl;
 cout << “Semester:”<<semester<<endl;
}
                                                    9/27
Private
                                                   student
             members                 sid                   name
                                                               ...       average
                                          ...
                                       marks
 Private members cannot be             semester
 accessed from outside the class
                                                              year

 That’s why, we use public
 methods to access them
                             student (char [] id, char [] nama, int sem =1 , int yr = 1)
 compute_average(...)
 set_marks (...)
                               void print()
                                              ..
                              void compute_average()
                                           .


                                              ..
                              void set_marks. (float [])

Public members                                                   10/27
Another program example

main ()
{ student a_given_student (“9870025”, “Omar”, 2, 2);

// This is instantiation.
//The object a_given_student is created and the constructor is
//automatically called to initialise that data members of a_given_student with


// I want to change his semester to 3
a_given_student. semester = 3 // ILLEGAL

// why? Because semester is a private data member and cannot
//be accessed outside the class student
...
}                                                 11/27
Another program example
               Then, how can we access semester and change it?
  2 options:
  Option 1
  We must define a new function member (public) to access semester


class student
{ private:                      main ()
         ….                     {
                                student a_given_student (“9870025”, “Omar”, 2, 2);
         int semester;
         …
                                // I want to change his semester to 3
public: …
                                a_given_student. set_semester( 3 ) ;
void set_semester(int sem =1)
                                …
         {semester = sem;}
                                }
         …
};
                                                              12/27
Another program example

 Option 2

 We must change the access specifier of semester, and make it public.


class student                     main ()
{ private:                        {
          ….                      student a_given_student (“9870025”, “Omar”, 2, 2);
 public : int semester;
          …                       // I want to change his semester to 3
public: …                         a_given_student.semester = 3;
  void set_semester(int sem =1)   …
             {semester = sem;}    }
...};
              no need!

                                                                13/27
Constant Object

• Some objects need to be modifiable and some do not.
• The keyword const is used to specify an object is not modifiable, and any
    attempt to change the object will produce a syntax error. For example
    const Model m1; or Model const m1;
•   const objects can only invoke their const member functions.
        void showInfo() const
        { ……. }

•   const declaration is not required for constructors and destructors of const
    objects
         Model () const
         { ……… }
                                                              14/27
Constant objects


#include <iostream.h>                      void main()
class Part                                 {
{ private:                                   Part part1(8678, 222, 34.55);
    int modelnumber; int partnumber          Part const part2;
    double cost;                             part2.setpart(2345, 444, 99.90);
 public:
   Part(int mn, int pn, double c);             part1.showpart();
                                               part2.showpart()
  void setpart(int mn, int pn, double c)
const;                                     }

     void showpart() const;
};

// Implementation - refer to page 5
Lecture 9                                                   15/27
Constant objects

class Student
{private: int age;
          int semester;
          int year;
public:
        Student (int, int , int); // constructor

        void set_semester(int sem =1){semester=sem;}
               //to set semester with sem (1 by default)

        void print( ) const;
};
             // print is a constant function member
             // meaning, it cannot modify any of 16/27
             // the data members
Constant objects


 Student::Student (int sem=5, int ag=20, int yr =1)
 { age=ag;    year = yr;     semester = sem; }

 void Student::print( ) const
  { cout <<"AGE:"<<age<<endl
     <<"Year:"<<year<<endl<<"semester:"<<semester<< endl;
    semester = 10; // illegal
  }
              We cannot set any data member with a value
              why?

Cause print is const and therefore can just access data members
without altering their values
                                                 17/27
Constant objects


  int main()                                    Normally invalid
  {                                             why?
      student h1;
      const student h2 (4,4,4); // or student const h2(4,4,4);
      h1.set_semester(5); // valid
      h2.print(); // valid
      h2.set_semester(5);
      h2.print();
      h1.print();           Cause we choose h2 as a constant object
  }                         SO, there should be no member function
                            that can alter its data members

EXCEPTION, constructors can still be used by constant objects
                                               18/27
Constant objects


• Constructors and destructors are inherently non constant function
members


• Choose your function members that just query data members
to be constants
      Syntax:
    return_type function_name (type1 par1, ..) const
    {…     }
• If you choose to work with constant objects, normally all (but
constructor and destructor) your function members should be
constants                                         19/27
Array of Objects              (page87-88)




class Student                                      Student
{ private:
                                             sid              name
        char sid[20];                           ...             ...
        char name[20];                       sem
        int sem;
                                           Student(...)
 public:                                   void print()
   Student (char [], char [], int);
   void print( ) ;                    void set_semester(int)
                                       .
   void set_semester(int s )           .
                                       .
   {    sem = s;}
};
                                                      20/27
int main ()
{
student FIT[3];     // declares an array called FIT with three elements
                  // the elements are objects of type (class) student

FIT[1].set_semester(2); // access the 2nd object of the array
                       // and invokes its method member to set
                      // its data member

...
}

                                                    21/27
Array Name
                 FIT
                             index
            0                               1                          2

    sid             name        sid             name       sid             name
          ...          ...            ...          ...           ...          ...
    sem                         sem         3              sem
     student(...)                student(...)               student(...)

     void print()                void print()               void print()

  void set_semester()         void set_semester()        void set_semester()



   1st array element           2nd array element          3rd array element
I want to set the semester of the 2nd array element with 3
                                                            22/27
                     FIT[1].set_semester(3)
Objects As Function Arguments:
             A Diagram (page133-144)
                  dist3.add_dist(dist1, dist2)

dist3             feet       inches


  dist1                      dist2
      feet      inches               feet        inches




 add_dist(Distance, Distance);    add_dist(Distance, Distance);



    inches = dist1.inches + dist2.inches;

             add_dist(Distance, Distance);
                                     23/27
Objects As Function Arguments:
                     A Program

#include <iostream.h>

class Distance
{
  public:
    Distance();            // default constructor
    Distance(int, float); // two-argument constructor
    void getdist();
    void showdist();
    void add_dist(Distance, Distance);

  private:
    int feet;
    float inches;
};
                                        24/27
Objects As Function Arguments:
                       A Program

Distance::Distance() { feet = 0; inches = 0;     }

Distance::Distance(int ft, float in): feet(ft),inches(in)
{ }

void Distance::getdist()
{
      cout << "nEnter feet: "; cin feet;
      cout << "Enter inches: "; cin inches;
}

void Distance::showdist()
{
      cout << feet << "'-" << inches << '"';
}
                                           25/27
Objects As Function Arguments:
                     A Program


void Distance::add_dist(Distance d1,   Distance d2)
{
  inches = d1.inches + d2.inches;
  feet = 0;
  if (inches = 12.0) {
    inches = inches - 12.0;
    feet++;
    }
  feet = feet + (d1.feet + d2.feet);
}




                                          26/27
Objects As Function Arguments:
                      A Program

int main()
{ Distance dist1, dist3;
   Distance dist2(11, 6.25);
   dist1.getdist();       //get dist1 from user
   dist3.add_dist(dist1, dist2);
   cout << "ndist1 = "; dist1.showdist();
   cout << "ndist2 = "; dist2.showdist();
   cout << "ndist3 = "; dist3.showdist();
   cout << endl;
   return 0;        dist1             dist2         dist3
}             feet = 0            feet = 11     feet = 0
               inches = 0             inches = 6.25            inches = 0
               Distance()             Distance()               Distance()
               Distance(int, float)   Distance(int, float)     Distance(int, float)
               void getdist()         void getdist()           void getdist()
               void showdist()        void showdist()          void showdist()
               void add_dist()        void add_dist()      27/27 add_dist()
                                                               void
Returning Objects From Functions
                   A Diagram
             dist3 = dist1.add_dist(dist2)

dist1           feet       inches


  dist2                     temp
      feet    inches               feet      inches




    add_dist(Distance);         add_dist(Distance);


  temp.inches = inches + dist2.inches;
  return temp;

              add_dist(Distance);
                                             28/27
Returning Objects From Functions
                       Example
class Distance
{ . . .
   Distance add_dist(Distance);
};

Distance Distance::add_dist(Distance d2)
{
  Distance temp;
  temp.inches = inches + d2.inches;
  if(temp.inches = 12.0) {
    temp.inches -= 12.0;
    temp.feet = 1;             int main()
  }                            { . . .
  temp.feet += feet+d2.feet;   dist3=dist1.add_dist(dist2);
  return temp;                   . . .
}                              }
                                           29/27

More Related Content

PPT
Lecture07
elearning_portal
 
PDF
Op ps
Shehzad Rizwan
 
PPT
object oriented programming language by c++
Mohamad Al_hsan
 
PPT
08slide
Dorothea Chaffin
 
PPT
Java căn bản - Chapter4
Vince Vo
 
PPT
11slide
Dorothea Chaffin
 
PPT
Lecture18
elearning_portal
 
PPTX
Ch.1 oop introduction, classes and objects
ITNet
 
Lecture07
elearning_portal
 
object oriented programming language by c++
Mohamad Al_hsan
 
Java căn bản - Chapter4
Vince Vo
 
Lecture18
elearning_portal
 
Ch.1 oop introduction, classes and objects
ITNet
 

What's hot (20)

PPT
10slide
Dorothea Chaffin
 
PPTX
14 Defining Classes
Intro C# Book
 
PDF
RNN sharing at Trend Micro
Chun Hao Wang
 
PDF
Object oriented programming
Renas Rekany
 
PDF
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
PDF
Oop03 6
schwaa
 
PPTX
Learning C++ - Class 4
Ali Aminian
 
PDF
Module wise format oops questions
SANTOSH RATH
 
PPT
C++ Inheritance
Jussi Pohjolainen
 
PPSX
Support for Object-Oriented Programming (OOP) in C++
Ameen Sha'arawi
 
PDF
Spark AI 2020
Li Jin
 
PPT
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
PPT
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
PPTX
Classes and objects in c++
Rokonuzzaman Rony
 
PDF
Java unit2
Abhishek Khune
 
PPTX
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
PPTX
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
DOCX
Advanced data structures using c++ 3
Shaili Choudhary
 
PDF
C++ Multiple Inheritance
harshaltambe
 
PPT
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
14 Defining Classes
Intro C# Book
 
RNN sharing at Trend Micro
Chun Hao Wang
 
Object oriented programming
Renas Rekany
 
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
Oop03 6
schwaa
 
Learning C++ - Class 4
Ali Aminian
 
Module wise format oops questions
SANTOSH RATH
 
C++ Inheritance
Jussi Pohjolainen
 
Support for Object-Oriented Programming (OOP) in C++
Ameen Sha'arawi
 
Spark AI 2020
Li Jin
 
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Classes and objects in c++
Rokonuzzaman Rony
 
Java unit2
Abhishek Khune
 
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Advanced data structures using c++ 3
Shaili Choudhary
 
C++ Multiple Inheritance
harshaltambe
 
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
Ad

Viewers also liked (14)

PPTX
Php Training Session 4
Vishal Kothari
 
PPTX
concept of oops
prince sharma
 
PDF
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
PPSX
String and string manipulation x
Shahjahan Samoon
 
PDF
Oops (inheritance&interface)
Muthukumaran Subramanian
 
ODP
Session Management & Cookies In Php
Harit Kothari
 
PDF
Java packages and access specifiers
ashishspace
 
PPTX
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
PPTX
OOPS IN C++
Amritsinghmehra
 
PPTX
Cookie and session
Aashish Ghale
 
PPT
Object Oriented Programming with Java
backdoor
 
PPTX
Cookies PowerPoint
emurfield
 
PPT
Cookies and sessions
Lena Petsenchuk
 
PPTX
oops concept in java | object oriented programming in java
CPD INDIA
 
Php Training Session 4
Vishal Kothari
 
concept of oops
prince sharma
 
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
String and string manipulation x
Shahjahan Samoon
 
Oops (inheritance&interface)
Muthukumaran Subramanian
 
Session Management & Cookies In Php
Harit Kothari
 
Java packages and access specifiers
ashishspace
 
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
OOPS IN C++
Amritsinghmehra
 
Cookie and session
Aashish Ghale
 
Object Oriented Programming with Java
backdoor
 
Cookies PowerPoint
emurfield
 
Cookies and sessions
Lena Petsenchuk
 
oops concept in java | object oriented programming in java
CPD INDIA
 
Ad

Similar to Lecture09 (20)

PPT
Lecture10
elearning_portal
 
PPTX
class and objects
Payel Guria
 
PDF
Implementation of oop concept in c++
Swarup Kumar Boro
 
PPT
Lecture19
elearning_portal
 
PPTX
Inheritance
Tech_MX
 
PPSX
Arre tari mano bhosko ka pikina tari ma no piko
kongshi9999
 
PPTX
More on Classes and Objects
Payel Guria
 
ODP
Class&objects
harivng
 
PPT
classes data type for Btech students.ppt
soniasharmafdp
 
DOC
Brief Summary Of C++
Haris Lye
 
PDF
C++ largest no between three nos
krismishra
 
PPTX
+2 CS class and objects
khaliledapal
 
PPT
Class and object in C++
rprajat007
 
PPT
Lecture 12: Classes and Files
Dr. Md. Shohel Sayeed
 
PPTX
Classes and objects till 16 aug
shashank12march
 
PDF
C++ Notes
MOHAMED RIYAZUDEEN
 
PPT
Lecture21
elearning_portal
 
PDF
Chapter 12 PJPK SDSDRFHVRCHVFHHVDRHVDRVHGVD
azimah6642
 
PPT
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
PPT
cpp class unitdfdsfasadfsdASsASass 4.ppt
nandemprasanna
 
Lecture10
elearning_portal
 
class and objects
Payel Guria
 
Implementation of oop concept in c++
Swarup Kumar Boro
 
Lecture19
elearning_portal
 
Inheritance
Tech_MX
 
Arre tari mano bhosko ka pikina tari ma no piko
kongshi9999
 
More on Classes and Objects
Payel Guria
 
Class&objects
harivng
 
classes data type for Btech students.ppt
soniasharmafdp
 
Brief Summary Of C++
Haris Lye
 
C++ largest no between three nos
krismishra
 
+2 CS class and objects
khaliledapal
 
Class and object in C++
rprajat007
 
Lecture 12: Classes and Files
Dr. Md. Shohel Sayeed
 
Classes and objects till 16 aug
shashank12march
 
Lecture21
elearning_portal
 
Chapter 12 PJPK SDSDRFHVRCHVFHHVDRHVDRVHGVD
azimah6642
 
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
cpp class unitdfdsfasadfsdASsASass 4.ppt
nandemprasanna
 

More from elearning_portal (9)

PPT
Lecture05
elearning_portal
 
PPT
Lecture17
elearning_portal
 
PPT
Lecture16
elearning_portal
 
PPT
Lecture06
elearning_portal
 
PPT
Lecture20
elearning_portal
 
PPT
Lecture03
elearning_portal
 
PPT
Lecture02
elearning_portal
 
PPT
Lecture01
elearning_portal
 
PPT
Lecture04
elearning_portal
 
Lecture05
elearning_portal
 
Lecture17
elearning_portal
 
Lecture16
elearning_portal
 
Lecture06
elearning_portal
 
Lecture20
elearning_portal
 
Lecture03
elearning_portal
 
Lecture02
elearning_portal
 
Lecture01
elearning_portal
 
Lecture04
elearning_portal
 

Recently uploaded (20)

PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Understanding operators in c language.pptx
auteharshil95
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 

Lecture09

  • 1. Lecture 09 Classes and Objects Learn about: i) More info on member access specifiers ii) Constant Objects and Functions iii) Array of Objects iv) Objects as Function Arguments v) Returning Objects from Functions 1/27
  • 2. Access Specifiers • What is access specifier? – It is the one which specifies which member can be accessed at which place. – Types of access specifiers : Data Hiding • There are three namely, ob1 ob2 – Private Friend Ob – Public » A class's public members can be accessed by any function in a program. Used as an interface of the class - Other objects can use it . – Protected. 2/27
  • 3. Member access specifiers (page164-176) Kitty friend of Kitty Snoopy public public public private private private 3/27
  • 4. How to access the members ? • If the data members of the class is – Private : • Cannot access directly outside the class • How to access ? – We should use member functions to access it. – EG : data member ----> int a; » int main( ) » { object name.member function( argument ) } – Public : • can access outside the class • EG : object name . Datamembername = value; » ob1.a = 9; 4/27 Example - Next slide
  • 5. A Simple Class #include <iostream.h> class Student // class declaration { can only be accessed within class private: int idNum; //class data members double gpa; accessible from outside and within class public: void setData(int id, double result) { idNum = id; gpa = result; } void showData() { cout << ”Student Id is ” << idNum << endl; cout << ”GPA is " << gpa << endl; } }; 5/27
  • 6. A simple program example #include <iostream.h> void main() { class Student Student s1, s2, s3; { s1.setData(10016666, 3.14); public: s2.setData(10011776, 3.55); int idNum; double gpa; s3.idNum = 10011886; void setData(int, double); s3.gpa = 3.22; void showData(); }; : : Okay, because idNum } and gpa are public. //Implementation - refer to notes page 1 (Lecture 9). 6/27
  • 7. A simple program example #include <iostream.h> void main() { class Student Student s1, s2, s3; { s1.setData(10016666, 3.14); private: s2.setData(10011776, 3.55); int idNum; double gpa; s3.idNum = 10011886; public: s3.gpa = 3.22; void setData(int, double); void showData(); : }; : Error!!! idNum } and gpa are private. //Implementation - refer to notes page 1 7/27 (Lecture 9).
  • 8. Another program example class student { private: char sid[20]; char name[20]; int semester; int year; float marks[4]; float average; public: // … student (char [], char [], int sem =1 , int yr = 1); void print( ) ; void compute_average( ) { average = (marks[0]+ marks[1]+ marks[2]+ marks[3])/4; } }; 8/27
  • 9. Another program example // class function members implementation default arguments student :: student (char id[20], char nama[20], int sem =1 , int yr = 1 ) { strcpy (name, nama); strcpy (sid, id); year = yr; semester = sem; } void student :: print ( ) { cout << “Student Id:”<<sid<<endl; cout << “Student Name:”<<name<<endl; cout << “Semester:”<<semester<<endl; } 9/27
  • 10. Private student members sid name ... average ... marks Private members cannot be semester accessed from outside the class year That’s why, we use public methods to access them student (char [] id, char [] nama, int sem =1 , int yr = 1) compute_average(...) set_marks (...) void print() .. void compute_average() . .. void set_marks. (float []) Public members 10/27
  • 11. Another program example main () { student a_given_student (“9870025”, “Omar”, 2, 2); // This is instantiation. //The object a_given_student is created and the constructor is //automatically called to initialise that data members of a_given_student with // I want to change his semester to 3 a_given_student. semester = 3 // ILLEGAL // why? Because semester is a private data member and cannot //be accessed outside the class student ... } 11/27
  • 12. Another program example Then, how can we access semester and change it? 2 options: Option 1 We must define a new function member (public) to access semester class student { private: main () …. { student a_given_student (“9870025”, “Omar”, 2, 2); int semester; … // I want to change his semester to 3 public: … a_given_student. set_semester( 3 ) ; void set_semester(int sem =1) … {semester = sem;} } … }; 12/27
  • 13. Another program example Option 2 We must change the access specifier of semester, and make it public. class student main () { private: { …. student a_given_student (“9870025”, “Omar”, 2, 2); public : int semester; … // I want to change his semester to 3 public: … a_given_student.semester = 3; void set_semester(int sem =1) … {semester = sem;} } ...}; no need! 13/27
  • 14. Constant Object • Some objects need to be modifiable and some do not. • The keyword const is used to specify an object is not modifiable, and any attempt to change the object will produce a syntax error. For example const Model m1; or Model const m1; • const objects can only invoke their const member functions. void showInfo() const { ……. } • const declaration is not required for constructors and destructors of const objects Model () const { ……… } 14/27
  • 15. Constant objects #include <iostream.h> void main() class Part { { private: Part part1(8678, 222, 34.55); int modelnumber; int partnumber Part const part2; double cost; part2.setpart(2345, 444, 99.90); public: Part(int mn, int pn, double c); part1.showpart(); part2.showpart() void setpart(int mn, int pn, double c) const; } void showpart() const; }; // Implementation - refer to page 5 Lecture 9 15/27
  • 16. Constant objects class Student {private: int age; int semester; int year; public: Student (int, int , int); // constructor void set_semester(int sem =1){semester=sem;} //to set semester with sem (1 by default) void print( ) const; }; // print is a constant function member // meaning, it cannot modify any of 16/27 // the data members
  • 17. Constant objects Student::Student (int sem=5, int ag=20, int yr =1) { age=ag; year = yr; semester = sem; } void Student::print( ) const { cout <<"AGE:"<<age<<endl <<"Year:"<<year<<endl<<"semester:"<<semester<< endl; semester = 10; // illegal } We cannot set any data member with a value why? Cause print is const and therefore can just access data members without altering their values 17/27
  • 18. Constant objects int main() Normally invalid { why? student h1; const student h2 (4,4,4); // or student const h2(4,4,4); h1.set_semester(5); // valid h2.print(); // valid h2.set_semester(5); h2.print(); h1.print(); Cause we choose h2 as a constant object } SO, there should be no member function that can alter its data members EXCEPTION, constructors can still be used by constant objects 18/27
  • 19. Constant objects • Constructors and destructors are inherently non constant function members • Choose your function members that just query data members to be constants Syntax: return_type function_name (type1 par1, ..) const {… } • If you choose to work with constant objects, normally all (but constructor and destructor) your function members should be constants 19/27
  • 20. Array of Objects (page87-88) class Student Student { private: sid name char sid[20]; ... ... char name[20]; sem int sem; Student(...) public: void print() Student (char [], char [], int); void print( ) ; void set_semester(int) . void set_semester(int s ) . . { sem = s;} }; 20/27
  • 21. int main () { student FIT[3]; // declares an array called FIT with three elements // the elements are objects of type (class) student FIT[1].set_semester(2); // access the 2nd object of the array // and invokes its method member to set // its data member ... } 21/27
  • 22. Array Name FIT index 0 1 2 sid name sid name sid name ... ... ... ... ... ... sem sem 3 sem student(...) student(...) student(...) void print() void print() void print() void set_semester() void set_semester() void set_semester() 1st array element 2nd array element 3rd array element I want to set the semester of the 2nd array element with 3 22/27 FIT[1].set_semester(3)
  • 23. Objects As Function Arguments: A Diagram (page133-144) dist3.add_dist(dist1, dist2) dist3 feet inches dist1 dist2 feet inches feet inches add_dist(Distance, Distance); add_dist(Distance, Distance); inches = dist1.inches + dist2.inches; add_dist(Distance, Distance); 23/27
  • 24. Objects As Function Arguments: A Program #include <iostream.h> class Distance { public: Distance(); // default constructor Distance(int, float); // two-argument constructor void getdist(); void showdist(); void add_dist(Distance, Distance); private: int feet; float inches; }; 24/27
  • 25. Objects As Function Arguments: A Program Distance::Distance() { feet = 0; inches = 0; } Distance::Distance(int ft, float in): feet(ft),inches(in) { } void Distance::getdist() { cout << "nEnter feet: "; cin feet; cout << "Enter inches: "; cin inches; } void Distance::showdist() { cout << feet << "'-" << inches << '"'; } 25/27
  • 26. Objects As Function Arguments: A Program void Distance::add_dist(Distance d1, Distance d2) { inches = d1.inches + d2.inches; feet = 0; if (inches = 12.0) { inches = inches - 12.0; feet++; } feet = feet + (d1.feet + d2.feet); } 26/27
  • 27. Objects As Function Arguments: A Program int main() { Distance dist1, dist3; Distance dist2(11, 6.25); dist1.getdist(); //get dist1 from user dist3.add_dist(dist1, dist2); cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); cout << "ndist3 = "; dist3.showdist(); cout << endl; return 0; dist1 dist2 dist3 } feet = 0 feet = 11 feet = 0 inches = 0 inches = 6.25 inches = 0 Distance() Distance() Distance() Distance(int, float) Distance(int, float) Distance(int, float) void getdist() void getdist() void getdist() void showdist() void showdist() void showdist() void add_dist() void add_dist() 27/27 add_dist() void
  • 28. Returning Objects From Functions A Diagram dist3 = dist1.add_dist(dist2) dist1 feet inches dist2 temp feet inches feet inches add_dist(Distance); add_dist(Distance); temp.inches = inches + dist2.inches; return temp; add_dist(Distance); 28/27
  • 29. Returning Objects From Functions Example class Distance { . . . Distance add_dist(Distance); }; Distance Distance::add_dist(Distance d2) { Distance temp; temp.inches = inches + d2.inches; if(temp.inches = 12.0) { temp.inches -= 12.0; temp.feet = 1; int main() } { . . . temp.feet += feet+d2.feet; dist3=dist1.add_dist(dist2); return temp; . . . } } 29/27