SlideShare a Scribd company logo
1 of 29
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

What's hot

RNN sharing at Trend Micro
RNN sharing at Trend MicroRNN sharing at Trend Micro
RNN sharing at Trend MicroChun Hao Wang
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Oop03 6
Oop03 6Oop03 6
Oop03 6schwaa
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questionsSANTOSH RATH
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Ameen Sha'arawi
 
Spark AI 2020
Spark AI 2020Spark AI 2020
Spark AI 2020Li Jin
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Abou Bakr Ashraf
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritanceharshaltambe
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)farhan amjad
 

What's hot (20)

10slide
10slide10slide
10slide
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
RNN sharing at Trend Micro
RNN sharing at Trend MicroRNN sharing at Trend Micro
RNN sharing at Trend Micro
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Oop03 6
Oop03 6Oop03 6
Oop03 6
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questions
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 
Spark AI 2020
Spark AI 2020Spark AI 2020
Spark AI 2020
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Java unit2
Java unit2Java unit2
Java unit2
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 

Viewers also liked

Php Training Session 4
Php Training Session 4Php Training Session 4
Php Training Session 4Vishal Kothari
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In PhpHarit Kothari
 
Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiersashishspace
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPointemurfield
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 

Viewers also liked (14)

Php Training Session 4
Php Training Session 4Php Training Session 4
Php Training Session 4
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Oops (inheritance&interface)
Oops (inheritance&interface)Oops (inheritance&interface)
Oops (inheritance&interface)
 
Session Management & Cookies In Php
Session Management & Cookies In PhpSession Management & Cookies In Php
Session Management & Cookies In Php
 
Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiers
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Cookies PowerPoint
Cookies PowerPointCookies PowerPoint
Cookies PowerPoint
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 

Similar to Lecture09

Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.pptBArulmozhi
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfstudy material
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Boro
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialskailash454
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialskksupaul
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectsecondakay
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-classDeepak Singh
 

Similar to Lecture09 (20)

Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
L10
L10L10
L10
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes
C++ classesC++ classes
C++ classes
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
 
02.adt
02.adt02.adt
02.adt
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
 

More from elearning_portal (11)

Lecture05
Lecture05Lecture05
Lecture05
 
Lecture21
Lecture21Lecture21
Lecture21
 
Lecture19
Lecture19Lecture19
Lecture19
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture16
Lecture16Lecture16
Lecture16
 
Lecture06
Lecture06Lecture06
Lecture06
 
Lecture20
Lecture20Lecture20
Lecture20
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture04
Lecture04Lecture04
Lecture04
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

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