SlideShare ist ein Scribd-Unternehmen logo
1 von 115
Object-Oriented Programming
           (OOP)
        Lecture No. 1
Course Objective

► Objective of this course is to make students
 familiar with the concepts of object-oriented
 programming

► Concepts
         will be reinforced by their
 implementation in C++
Course Contents
► Object-Orientation
► Objects and Classes
► Overloading
► Inheritance
► Polymorphism
► Generic Programming
► Exception Handling
► Introduction to Design Patterns
Books
► C++   How to Program
  By Deitel & Deitel


► The   C++ Programming Language
  By Bjarne Stroustrup


► Object-Oriented      Software Engineering
  By Jacobson, Christerson, Jonsson, Overgaard
Object-Orientation (OO)
What is Object-Orientation?

►A   technique for system modeling

► OO model consists of several interacting
 objects
What is a Model?

►A   model is an abstraction of something

► Purposeis to understand the product before
 developing it
Examples – Model

► Highway   maps

► Architectural   models

► Mechanical   models
Example – OO Model
…Example – OO Model
► Objects                               lives-in
                             Ali                   House
     Ali
                               drives
     House
     Car
                             Car                   Tree
     Tree
► Interactions
   Ali lives in the house
   Ali drives the car
Object-Orientation - Advantages
► People   think in terms of objects

► OO   models map to reality

► Therefore,   OO models are
   easy to develop
   easy to understand
What is an Object?
An object is

► Something    tangible (Ali, Car)

► Something   that can be apprehended
 intellectually (Time, Date)
… What is an Object?
An object has

► State (attributes)
► Well-defined behaviour (operations)
► Unique identity
Example – Ali is a Tangible Object
► State   (attributes)
     Name
     Age
► behaviour    (operations)
   Walks
   Eats
► Identity
   His name
Example – Car is a Tangible Object
► State   (attributes)
  - Color
  - Model
► behaviour   (operations)
  - Accelerate           - Start Car
  - Change Gear
► Identity
  - Its registration number
Example – Time is an Object
      Apprehended Intellectually
► State   (attributes)
  - Hours                - Seconds
  - Minutes
► behaviour   (operations)
  - Set Hours            - Set Seconds
  - Set Minutes
► Identity
  - Would have a unique ID in the model
Example – Date is an Object
        Apprehended Intellectually
► State   (attributes)
  -   Year               - Day
  -   Month
► behaviour   (operations)
  - Set Year             - Set Day
  - Set Month
► Identity
  - Would have a unique ID in the model
Object-Oriented Programming
           (OOP)
        Lecture No. 2
Information Hiding

► Information    is stored within the object

► It   is hidden from the outside world

► It can only be manipulated by the object
  itself
Example – Information Hiding

► Ali’s   name is stored within his brain

► We      can’t access his name directly

► Rather     we can ask him to tell his name
Example – Information Hiding

►A   phone stores several phone numbers

► Wecan’t read the numbers directly from the
 SIM card

► Rather   phone-set reads this information for
 us
Information Hiding
                 Advantages

► Simplifies
          the model by hiding
  implementation details

► It   is a barrier against change propagation
Encapsulation

► Data and behaviour are tightly coupled
 inside an object

► Boththe information structure and
 implementation details of its operations are
 hidden from the outer world
Example – Encapsulation

► Alistores his personal information and
  knows how to translate it to the desired
  language

► We    don’t know
   How the data is stored
   How Ali translates this information
Example – Encapsulation
►A Phone stores phone numbers in digital
 format and knows how to convert it into
 human-readable characters

► We   don’t know
  How the data is stored
  How it is converted to human-readable
   characters
Encapsulation – Advantages

► Simplicity   and clarity

► Low   complexity

► Better   understanding
Object has an Interface

► An  object encapsulates data and behaviour
► So how objects interact with each other?
► Each object provides an interface
  (operations)
► Other objects communicate through this
  interface
Example – Interface of a Car
► Steer Wheels
► Accelerate
► Change Gear
► Apply Brakes
► Turn Lights On/Off
Example – Interface of a Phone
► Input Number
► Place Call
► Disconnect Call
► Add number to address book
► Remove number
► Update number
Implementation
► Provides   services offered by the object
 interface

► This   includes
   Data structures to hold object state
   Functionality that provides required services
Example – Implementation of
            Gear Box

► Data   Structure
   Mechanical structure of gear box


► Functionality
   Mechanism to change gear
Example – Implementation of
     Address Book in a Phone

► Data   Structure
   SIM card


► Functionality
   Read/write circuitry
Separation of Interface &
         Implementation

► Means  change in implementation does not
 effect object interface

► Thisis achieved via principles of information
 hiding and encapsulation
Example – Separation of
     Interface & Implementation

►A driver can drive a car independent of
 engine type (petrol, diesel)

► Because
        interface does not change with the
 implementation
Example – Separation of
     Interface & Implementation

►A driver can apply brakes independent of
 brakes type (simple, disk)

► Again,   reason is the same interface
Advantages of Separation
► Users need not to worry about a change
 until the interface is same

► Low   Complexity

► Directaccess to information structure of an
 object can produce errors
Messages

► Objects  communicate through messages
► They send messages (stimuli) by invoking
  appropriate operations on the target object
► The number and kind of messages that can
  be sent to an object depends upon its
  interface
Examples – Messages

►A Person sends message (stimulus) “stop”
 to a Car by applying brakes

►A Person sends message “place call” to a
 Phone by pressing appropriate button
Object-Oriented Programming
           (OOP)
        Lecture No. 3
Abstraction

► Abstraction   is a way to cope with
  complexity.

► Principle   of abstraction:

 “Capture only those details about an object
   that are relevant to current perspective”
Example – Abstraction
 Ali is a PhD student and teaches BS
 students

► Attributes
  -   Name                   -   Employee ID
  -   Student Roll No        -   Designation
  -   Year of Study          -   Salary
  -   CGPA                   -   Age
Example – Abstraction
 Ali is a PhD student and teaches BS
 students

► behaviour
  -   Study             -   DevelopExam
  -   GiveExam          -   TakeExam
  -   PlaySports        -   Eat
  -   DeliverLecture    -   Walk
Example – Abstraction
               Student’s Perspective


► Attributes
  -   Name                      -   Employee ID
  -   Student Roll No           -   Designation
  -   Year of Study             -   Salary
  -   CGPA                      -   Age
Example – Abstraction
               Student’s Perspective


► behaviour
  -   Study                -   DevelopExam
  -   GiveExam             -   TakeExam
  -   PlaySports           -   Eat
  -   DeliverLecture       -   Walk
Example – Abstraction
               Teacher’s Perspective


► Attributes
  -   Name                     -   Employee ID
  -   Student Roll No          -   Designation
  -   Year of Study            -   Salary
  -   CGPA                     -   Age
Example – Abstraction
               Teacher’s Perspective


► behaviour
  -   Study                -   DevelopExam
  -   GiveExam             -   TakeExam
  -   PlaySports           -   Eat
  -   DeliverLecture       -   Walk
Example – Abstraction
   A cat can be viewed with different
   perspectives

► Ordinary   Perspective   ► Surgeon’s   Perspective
  A pet animal with          A being with
   Four Legs                 A Skeleton
   A Tail                    Heart
   Two Ears                  Kidney
   Sharp Teeth               Stomach
Example – Abstraction



                         Engineer’s View


Driver’s View
Abstraction – Advantages

► Simplifies   the model by hiding irrelevant
  details

► Abstraction
            provides the freedom to defer
  implementation decisions by avoiding
  commitment to details
Classes

► Inan OO model, some of the objects exhibit
 identical characteristics (information
 structure and behaviour)

► We   say that they belong to the same class
Example – Class
► Ali
    studies mathematics
► Anam studies physics
► Sohail studies chemistry


► Each one is a Student
► We say these objects are instances of the
  Student class
Example – Class
► Ahsan   teaches mathematics
► Aamir teaches computer science
► Atif teaches physics


► Each one is a teacher
► We say these objects are instances of the
  Teacher class
Graphical Representation of Classes


  (Class Name)
                     (Class Name)
  (attributes)

                      Suppressed
  (operations)
                         Form

  Normal Form
Example – Graphical Representation
            of Classes

     Circle
   center              Circle
   radius
   draw              Suppressed
   computeArea          Form

  Normal Form
Example – Graphical Representation
            of Classes

     Person
    name              Person
    age
    gender          Suppressed
    eat                Form
    walk

  Normal Form
Inheritance

►A   child inherits characteristics of its parents

► Besides
        inherited characteristics, a child
 may have its own unique characteristics
Inheritance in Classes
► If a class B inherits from class A then it
  contains all the characteristics (information
  structure and behaviour) of class A
► The parent class is called base class and the
  child class is called derived class
► Besides inherited characteristics, derived
  class may have its own unique
  characteristics
Example – Inheritance

          Person



Student             Doctor
          Teacher
Example – Inheritance

       Shape



Line             Triangle
        Circle
Inheritance – “IS A” or
     “IS A KIND OF” Relationship

► Eachderived class is a special kind of its
 base class
Example – “IS A” Relationship
               Person
             name
             age
             gender
             eat
             walk



  Student     Teacher        Doctor
program     designation   designation
studyYear   salary        salary
study       teach         checkUp
heldExam    takeExam      prescribe
Example – “IS A” Relationship
                 Shape
                color
                coord
                draw
                rotate
                setColor




   Circle                    Triangle
radius             Line    angle
draw          length       draw
computeArea   draw         computeArea
Inheritance – Advantages

► Reuse


► Less   redundancy

► Increased   maintainability
Reuse with Inheritance
► Main purpose of inheritance is reuse
► We can easily add new classes by inheriting
  from existing classes
   Select an existing class closer to the desired
    functionality
   Create a new class and inherit it from the
    selected class
   Add to and/or modify the inherited functionality
Example Reuse
                    Shape
                   color
                   coord
                   draw
                   rotate
                   setColor




   Circle                       Triangle
radius                Line    angle
draw             length       draw
computeArea      draw         computeArea
Example Reuse
                 Person
               name
               age
               gender
               eat
               walk



  Student       Teacher        Doctor
program       designation   designation
studyYear     salary        salary
study         teach         checkUp
heldExam      takeExam      prescribe
Example Reuse
                 Person
               name
               age
               gender
               eat
               walk



  Student       Teacher        Doctor
program       designation   designation
studyYear     salary        salary
study         teach         checkUp
heldExam      takeExam      prescribe
Object-Oriented Programming
           (OOP)
        Lecture No. 4
Recap – Inheritance
► Derivedclass inherits all the characteristics
 of the base class

► Besidesinherited characteristics, derived
 class may have its own unique
 characteristics

► Major   benefit of inheritance is reuse
Concepts Related with
            Inheritance

► Generalization


► Subtyping   (extension)

► Specialization   (restriction)
Generalization
► In
   OO models, some classes may have
 common characteristics

► We extract these features into a new class
 and inherit original classes from this new
 class

► This   concept is known as Generalization
Example – Generalization
    Line
color
vertices        Circle
length       color
move         vertices        Triangle
setColor     radius
                           color
getLength    move
                           vertices
             setColor
                           angle
             computeArea
                           move
                           setColor
                           computeArea
Example – Generalization
                 Shape
                color
                vertices
                move
                setColor




   Circle                    Triangle
radius            Line     angle
computeArea   length       computeArea
              getLength
Example – Generalization
  Student
name
age           Teacher
gender      name
                             Doctor
program     age
                          name
studyYear   gender
                          age
study       designation
                          gender
heldExam    salary
                          designation
eat         teach
                          salary
walk        takeExam
            eat           checkUp
            walk          prescribe
                          eat
                          walk
Example – Generalization
               Person
             name
             age
             gender
             eat
             walk



  Student     Teacher        Doctor
program     designation   designation
studyYear   salary        salary
study       teach         checkUp
heldExam    takeExam      prescribe
Sub-typing & Specialization
► We want to add a new class to an existing
  model

► Find an existing class that already
  implements some of the desired state and
  behaviour

► Inheritthe new class from this class and
  add unique behaviour to the new class
Sub-typing (Extension)
► Sub-typingmeans that derived class is
 behaviourally compatible with the base class

► Behaviourallycompatible means that base
 class can be replaced by the derived class
Person
              name
              age
              gender
              eats
 Example –    walks

Sub-typing
(Extension)    Student
              program
              studyYear
              study
              takeExam
Shape
               color
               vertices
               setColor
 Example –     move

Sub-typing
(Extension)
                Circle
              radius
              computeCF
              computeArea
Specialization (Restriction)
► Specialization
               means that derived class is
 behaviourally incompatible with the base
 class

► Behaviourally incompatible means that base
 class can’t always be replaced by the
 derived class
Example – Specialization
     (Restriction)
    Person
age : [0..100]
…
setAge( a )        age = a
…



     Adult        If age < 18 then
age : [18..100]       error
…                 else
setAge( a )           age = a
…
Example – Specialization
     (Restriction)
  IntegerSet
…
add( elem )    add element
…              to the set



               If elem < 1 then
  NaturalSet       error
…              else
add( elem )        add element
…                  to the set
Overriding

►A class may need to override the default
 behaviour provided by its base class

► Reasons    for overriding
     Provide behaviour specific to a derived class
     Extend the default behaviour
     Restrict the default behaviour
     Improve performance
Example – Specific Behaviour
                 Shape
                color
                vertices
                draw
                move
                setColor




   Circle                    Triangle
radius             Line    angle
draw          length       draw
computeArea   draw         computeArea
Example – Extension
 Window
 width
 height
 open
 close
 draw



DialogBox       1- Invoke Window’s
controls            draw
enable          2- draw the dialog
draw            box
Example – Restriction
  IntegerSet
…
add( elem )    Add element
…              to the set



               If elem < 1 then
  NaturalSet       give error
…              else
add( elem )        Add element
…                  to the set
Example – Improve Performance
                               Shape
                              color
► Class Circle overrides      coord
  rotate operation of         draw
  class Shape with a Null     rotate
  operation.                  setColor



                                Circle
                            radius
                            draw
                            rotate
Abstract Classes

► An  abstract class implements an abstract
  concept
► Main purpose is to be inherited by other
  classes
► Can’t be instantiated
► Promotes reuse
Example – Abstract Classes
                    Person
                   name
                   age
                   gender
                   eat
                   walk


   Student                         Doctor
                   Teacher
► Here,   Person is an abstract class
Example – Abstract Classes
                    Vehicle
                  color
                  model
                  accelerate
                  applyBrakes


      Car                          Truck
                      Bus

► Here,   Vehicle is an abstract class
Concrete Classes
►A concrete class implements a concrete
 concept

► Main   purpose is to be instantiated

► Provides
         implementation details specific to
 the domain context
Example – Concrete Classes

                  Person


     Student                   Doctor
  program         Teacher
  studyYear
  study
  heldExam


► Here,Student, Teacher and Doctor are
 concrete classes
Example – Concrete Classes

               Vehicle


     Car                       Truck
                 Bus
                            capacity
                            load
                            unload


• Here, Car, Bus and Truck are concrete
  classes
Object oriented programming
            (OOP)
        Lecture No. 7
Class
► Class is a tool to realize objects
► Class is a tool for defining a new type
Example
► Lionis an object
► Student is an object
► Both has some attributes and some
  behaviors
Uses
► The  problem becomes easy to understand
► Interactions can be easily modeled
Type in C++
► Mechanism      for user defined types are
   Structures
   Classes
► Built-in
         types are like int, float and double
► User defined type can be
   Student in student management system
   Circle in a drawing software
Abstraction
► Only include details in the system that are
  required for making a functional system
► Student
     Name
                  Relevant to our problem
     Address
     Sibling
                              Not relevant to our problem
     Father Business
Defining a New User Defined Type

class ClassName
{            Syntax
  …
  DataType MemberVariable;
  ReturnType MemberFunction();
  …
};        Syntax
Example
class Student
{
  int rollNo;
  char *name;       Member variables
  float CGPA;




                                       Member Functions
  char *address;
…
  void setName(char *newName);
  void setRollNo(int newRollNo);
…
};
Why Member Function
► They model the behaviors of an object
► Objects can make their data invisible
► Object remains in consistent state
Example
Student aStudent;

aStudent.rollNo = 514;

aStudent.rollNo = -514; //Error
Object and Class
► Objectis an instantiation of a user defined
 type or a class
Declaring class variables
► Variables of classes (objects) are declared
 just like variables of structures and built-in
 data types

TypeName VaraibaleName;
int var;
Student aStudent;
Accessing members
► Members   of an object can be accessed
 using
   dot operator (.) to access via the variable name
   arrow operator (->) to access via a pointer to
    an object
► Member variables and member functions
 are accessed in a similar fashion
Example
class Student{
  int rollNo;
  void setRollNo(int
  aNo);
};

 Student aStudent;     Error
 aStudent.rollNo;
Access specifiers
Access specifiers
► There   are three access specifiers
   ‘public’ is used to tell that member can be
    accessed whenever you have access to the
    object
   ‘private’ is used to tell that member can only be
    accessed from a member function
   ‘protected’ to be discussed when we cover
    inheritance
Example
class Student{
private:
  char * name;
                  Cannot be accessed outside class
  int rollNo;
public:
  void setName(char *);             Can be
                                    accessed
  void setRollNo(int);              outside class
...
};
Example
class Student{
...
  int rollNo;
public:
  void setRollNo(int aNo);
};
int main(){
  Student aStudent;
  aStudent.SetRollNo(1);
}
Default access specifiers
► When no access specifier is mentioned then
 by default the member is considered private
 member
Example
class Student         class Student
{                     {
  char * name;        private:
  int RollNo;           char * name;
};                      int RollNo;
                      };
Example
class Student
{
  char * name;
  int RollNo;
  void SetName(char *);
};                        Error

Student aStudent;
aStudent.SetName(Ali);
Example
class Student
{
  char * name;
  int RollNo;
public:
  void setName(char *);
};
Student aStudent;
aStudent.SetName(“Ali”);

Weitere ähnliche Inhalte

Was ist angesagt?

Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented ParadigmHüseyin Ergin
 
Object orientation technology
Object orientation technologyObject orientation technology
Object orientation technologynaveed428
 
Handout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignHandout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignSAFAD ISMAIL
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programmingAbzetdin Adamov
 
Abstraction1
Abstraction1Abstraction1
Abstraction1zindadili
 
Lecture#01, object orientation
Lecture#01, object orientationLecture#01, object orientation
Lecture#01, object orientationbabak danyal
 

Was ist angesagt? (6)

Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented Paradigm
 
Object orientation technology
Object orientation technologyObject orientation technology
Object orientation technology
 
Handout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignHandout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and Design
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Lecture#01, object orientation
Lecture#01, object orientationLecture#01, object orientation
Lecture#01, object orientation
 

Ähnlich wie Lecture01

interface and implementation in java
interface and implementation in javainterface and implementation in java
interface and implementation in javaAbdul Wahab
 
Concept of Classes in c++.ist mse16.pptx
Concept of Classes in c++.ist mse16.pptxConcept of Classes in c++.ist mse16.pptx
Concept of Classes in c++.ist mse16.pptxsaadpisjes
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptxShuvrojitMajumder
 
Object oriented progrmming
Object oriented progrmmingObject oriented progrmming
Object oriented progrmmingAbdul Wahab
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)Jyoti shukla
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Conceptsmj
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptxVishwanathanS5
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iTaymoor Nazmy
 
C++ unit-1-part-3
C++ unit-1-part-3C++ unit-1-part-3
C++ unit-1-part-3Jadavsejal
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingManish Pandit
 
Object Modelling Technique " ooad "
Object Modelling Technique  " ooad "Object Modelling Technique  " ooad "
Object Modelling Technique " ooad "AchrafJbr
 

Ähnlich wie Lecture01 (20)

OOP Lecture 01.pptx
OOP Lecture 01.pptxOOP Lecture 01.pptx
OOP Lecture 01.pptx
 
interface and implementation in java
interface and implementation in javainterface and implementation in java
interface and implementation in java
 
Concept of Classes in c++.ist mse16.pptx
Concept of Classes in c++.ist mse16.pptxConcept of Classes in c++.ist mse16.pptx
Concept of Classes in c++.ist mse16.pptx
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptx
 
Object oriented progrmming
Object oriented progrmmingObject oriented progrmming
Object oriented progrmming
 
java
javajava
java
 
CS8592-OOAD Lecture Notes Unit-1
CS8592-OOAD Lecture Notes Unit-1CS8592-OOAD Lecture Notes Unit-1
CS8592-OOAD Lecture Notes Unit-1
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
 
Oop
OopOop
Oop
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Lec 09
Lec 09Lec 09
Lec 09
 
Lec5_OOP.pptx
Lec5_OOP.pptxLec5_OOP.pptx
Lec5_OOP.pptx
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
C++ unit-1-part-3
C++ unit-1-part-3C++ unit-1-part-3
C++ unit-1-part-3
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Object Modelling Technique " ooad "
Object Modelling Technique  " ooad "Object Modelling Technique  " ooad "
Object Modelling Technique " ooad "
 

Kürzlich hochgeladen

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Lecture01

  • 1. Object-Oriented Programming (OOP) Lecture No. 1
  • 2. Course Objective ► Objective of this course is to make students familiar with the concepts of object-oriented programming ► Concepts will be reinforced by their implementation in C++
  • 3. Course Contents ► Object-Orientation ► Objects and Classes ► Overloading ► Inheritance ► Polymorphism ► Generic Programming ► Exception Handling ► Introduction to Design Patterns
  • 4. Books ► C++ How to Program By Deitel & Deitel ► The C++ Programming Language By Bjarne Stroustrup ► Object-Oriented Software Engineering By Jacobson, Christerson, Jonsson, Overgaard
  • 6. What is Object-Orientation? ►A technique for system modeling ► OO model consists of several interacting objects
  • 7. What is a Model? ►A model is an abstraction of something ► Purposeis to understand the product before developing it
  • 8. Examples – Model ► Highway maps ► Architectural models ► Mechanical models
  • 10. …Example – OO Model ► Objects lives-in Ali House  Ali drives  House  Car Car Tree  Tree ► Interactions  Ali lives in the house  Ali drives the car
  • 11. Object-Orientation - Advantages ► People think in terms of objects ► OO models map to reality ► Therefore, OO models are  easy to develop  easy to understand
  • 12. What is an Object? An object is ► Something tangible (Ali, Car) ► Something that can be apprehended intellectually (Time, Date)
  • 13. … What is an Object? An object has ► State (attributes) ► Well-defined behaviour (operations) ► Unique identity
  • 14. Example – Ali is a Tangible Object ► State (attributes)  Name  Age ► behaviour (operations)  Walks  Eats ► Identity  His name
  • 15. Example – Car is a Tangible Object ► State (attributes) - Color - Model ► behaviour (operations) - Accelerate - Start Car - Change Gear ► Identity - Its registration number
  • 16. Example – Time is an Object Apprehended Intellectually ► State (attributes) - Hours - Seconds - Minutes ► behaviour (operations) - Set Hours - Set Seconds - Set Minutes ► Identity - Would have a unique ID in the model
  • 17. Example – Date is an Object Apprehended Intellectually ► State (attributes) - Year - Day - Month ► behaviour (operations) - Set Year - Set Day - Set Month ► Identity - Would have a unique ID in the model
  • 18. Object-Oriented Programming (OOP) Lecture No. 2
  • 19. Information Hiding ► Information is stored within the object ► It is hidden from the outside world ► It can only be manipulated by the object itself
  • 20. Example – Information Hiding ► Ali’s name is stored within his brain ► We can’t access his name directly ► Rather we can ask him to tell his name
  • 21. Example – Information Hiding ►A phone stores several phone numbers ► Wecan’t read the numbers directly from the SIM card ► Rather phone-set reads this information for us
  • 22. Information Hiding Advantages ► Simplifies the model by hiding implementation details ► It is a barrier against change propagation
  • 23. Encapsulation ► Data and behaviour are tightly coupled inside an object ► Boththe information structure and implementation details of its operations are hidden from the outer world
  • 24. Example – Encapsulation ► Alistores his personal information and knows how to translate it to the desired language ► We don’t know  How the data is stored  How Ali translates this information
  • 25. Example – Encapsulation ►A Phone stores phone numbers in digital format and knows how to convert it into human-readable characters ► We don’t know  How the data is stored  How it is converted to human-readable characters
  • 26. Encapsulation – Advantages ► Simplicity and clarity ► Low complexity ► Better understanding
  • 27. Object has an Interface ► An object encapsulates data and behaviour ► So how objects interact with each other? ► Each object provides an interface (operations) ► Other objects communicate through this interface
  • 28. Example – Interface of a Car ► Steer Wheels ► Accelerate ► Change Gear ► Apply Brakes ► Turn Lights On/Off
  • 29. Example – Interface of a Phone ► Input Number ► Place Call ► Disconnect Call ► Add number to address book ► Remove number ► Update number
  • 30. Implementation ► Provides services offered by the object interface ► This includes  Data structures to hold object state  Functionality that provides required services
  • 31. Example – Implementation of Gear Box ► Data Structure  Mechanical structure of gear box ► Functionality  Mechanism to change gear
  • 32. Example – Implementation of Address Book in a Phone ► Data Structure  SIM card ► Functionality  Read/write circuitry
  • 33. Separation of Interface & Implementation ► Means change in implementation does not effect object interface ► Thisis achieved via principles of information hiding and encapsulation
  • 34. Example – Separation of Interface & Implementation ►A driver can drive a car independent of engine type (petrol, diesel) ► Because interface does not change with the implementation
  • 35. Example – Separation of Interface & Implementation ►A driver can apply brakes independent of brakes type (simple, disk) ► Again, reason is the same interface
  • 36. Advantages of Separation ► Users need not to worry about a change until the interface is same ► Low Complexity ► Directaccess to information structure of an object can produce errors
  • 37. Messages ► Objects communicate through messages ► They send messages (stimuli) by invoking appropriate operations on the target object ► The number and kind of messages that can be sent to an object depends upon its interface
  • 38. Examples – Messages ►A Person sends message (stimulus) “stop” to a Car by applying brakes ►A Person sends message “place call” to a Phone by pressing appropriate button
  • 39. Object-Oriented Programming (OOP) Lecture No. 3
  • 40. Abstraction ► Abstraction is a way to cope with complexity. ► Principle of abstraction: “Capture only those details about an object that are relevant to current perspective”
  • 41. Example – Abstraction Ali is a PhD student and teaches BS students ► Attributes - Name - Employee ID - Student Roll No - Designation - Year of Study - Salary - CGPA - Age
  • 42. Example – Abstraction Ali is a PhD student and teaches BS students ► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
  • 43. Example – Abstraction Student’s Perspective ► Attributes - Name - Employee ID - Student Roll No - Designation - Year of Study - Salary - CGPA - Age
  • 44. Example – Abstraction Student’s Perspective ► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
  • 45. Example – Abstraction Teacher’s Perspective ► Attributes - Name - Employee ID - Student Roll No - Designation - Year of Study - Salary - CGPA - Age
  • 46. Example – Abstraction Teacher’s Perspective ► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
  • 47. Example – Abstraction A cat can be viewed with different perspectives ► Ordinary Perspective ► Surgeon’s Perspective A pet animal with A being with  Four Legs  A Skeleton  A Tail  Heart  Two Ears  Kidney  Sharp Teeth  Stomach
  • 48. Example – Abstraction Engineer’s View Driver’s View
  • 49. Abstraction – Advantages ► Simplifies the model by hiding irrelevant details ► Abstraction provides the freedom to defer implementation decisions by avoiding commitment to details
  • 50. Classes ► Inan OO model, some of the objects exhibit identical characteristics (information structure and behaviour) ► We say that they belong to the same class
  • 51. Example – Class ► Ali studies mathematics ► Anam studies physics ► Sohail studies chemistry ► Each one is a Student ► We say these objects are instances of the Student class
  • 52. Example – Class ► Ahsan teaches mathematics ► Aamir teaches computer science ► Atif teaches physics ► Each one is a teacher ► We say these objects are instances of the Teacher class
  • 53. Graphical Representation of Classes (Class Name) (Class Name) (attributes) Suppressed (operations) Form Normal Form
  • 54. Example – Graphical Representation of Classes Circle center Circle radius draw Suppressed computeArea Form Normal Form
  • 55. Example – Graphical Representation of Classes Person name Person age gender Suppressed eat Form walk Normal Form
  • 56. Inheritance ►A child inherits characteristics of its parents ► Besides inherited characteristics, a child may have its own unique characteristics
  • 57. Inheritance in Classes ► If a class B inherits from class A then it contains all the characteristics (information structure and behaviour) of class A ► The parent class is called base class and the child class is called derived class ► Besides inherited characteristics, derived class may have its own unique characteristics
  • 58. Example – Inheritance Person Student Doctor Teacher
  • 59. Example – Inheritance Shape Line Triangle Circle
  • 60. Inheritance – “IS A” or “IS A KIND OF” Relationship ► Eachderived class is a special kind of its base class
  • 61. Example – “IS A” Relationship Person name age gender eat walk Student Teacher Doctor program designation designation studyYear salary salary study teach checkUp heldExam takeExam prescribe
  • 62. Example – “IS A” Relationship Shape color coord draw rotate setColor Circle Triangle radius Line angle draw length draw computeArea draw computeArea
  • 63. Inheritance – Advantages ► Reuse ► Less redundancy ► Increased maintainability
  • 64. Reuse with Inheritance ► Main purpose of inheritance is reuse ► We can easily add new classes by inheriting from existing classes  Select an existing class closer to the desired functionality  Create a new class and inherit it from the selected class  Add to and/or modify the inherited functionality
  • 65. Example Reuse Shape color coord draw rotate setColor Circle Triangle radius Line angle draw length draw computeArea draw computeArea
  • 66. Example Reuse Person name age gender eat walk Student Teacher Doctor program designation designation studyYear salary salary study teach checkUp heldExam takeExam prescribe
  • 67. Example Reuse Person name age gender eat walk Student Teacher Doctor program designation designation studyYear salary salary study teach checkUp heldExam takeExam prescribe
  • 68. Object-Oriented Programming (OOP) Lecture No. 4
  • 69. Recap – Inheritance ► Derivedclass inherits all the characteristics of the base class ► Besidesinherited characteristics, derived class may have its own unique characteristics ► Major benefit of inheritance is reuse
  • 70. Concepts Related with Inheritance ► Generalization ► Subtyping (extension) ► Specialization (restriction)
  • 71. Generalization ► In OO models, some classes may have common characteristics ► We extract these features into a new class and inherit original classes from this new class ► This concept is known as Generalization
  • 72. Example – Generalization Line color vertices Circle length color move vertices Triangle setColor radius color getLength move vertices setColor angle computeArea move setColor computeArea
  • 73. Example – Generalization Shape color vertices move setColor Circle Triangle radius Line angle computeArea length computeArea getLength
  • 74. Example – Generalization Student name age Teacher gender name Doctor program age name studyYear gender age study designation gender heldExam salary designation eat teach salary walk takeExam eat checkUp walk prescribe eat walk
  • 75. Example – Generalization Person name age gender eat walk Student Teacher Doctor program designation designation studyYear salary salary study teach checkUp heldExam takeExam prescribe
  • 76. Sub-typing & Specialization ► We want to add a new class to an existing model ► Find an existing class that already implements some of the desired state and behaviour ► Inheritthe new class from this class and add unique behaviour to the new class
  • 77. Sub-typing (Extension) ► Sub-typingmeans that derived class is behaviourally compatible with the base class ► Behaviourallycompatible means that base class can be replaced by the derived class
  • 78. Person name age gender eats Example – walks Sub-typing (Extension) Student program studyYear study takeExam
  • 79. Shape color vertices setColor Example – move Sub-typing (Extension) Circle radius computeCF computeArea
  • 80. Specialization (Restriction) ► Specialization means that derived class is behaviourally incompatible with the base class ► Behaviourally incompatible means that base class can’t always be replaced by the derived class
  • 81. Example – Specialization (Restriction) Person age : [0..100] … setAge( a ) age = a … Adult If age < 18 then age : [18..100] error … else setAge( a ) age = a …
  • 82. Example – Specialization (Restriction) IntegerSet … add( elem ) add element … to the set If elem < 1 then NaturalSet error … else add( elem ) add element … to the set
  • 83. Overriding ►A class may need to override the default behaviour provided by its base class ► Reasons for overriding  Provide behaviour specific to a derived class  Extend the default behaviour  Restrict the default behaviour  Improve performance
  • 84. Example – Specific Behaviour Shape color vertices draw move setColor Circle Triangle radius Line angle draw length draw computeArea draw computeArea
  • 85. Example – Extension Window width height open close draw DialogBox 1- Invoke Window’s controls draw enable 2- draw the dialog draw box
  • 86. Example – Restriction IntegerSet … add( elem ) Add element … to the set If elem < 1 then NaturalSet give error … else add( elem ) Add element … to the set
  • 87. Example – Improve Performance Shape color ► Class Circle overrides coord rotate operation of draw class Shape with a Null rotate operation. setColor Circle radius draw rotate
  • 88. Abstract Classes ► An abstract class implements an abstract concept ► Main purpose is to be inherited by other classes ► Can’t be instantiated ► Promotes reuse
  • 89. Example – Abstract Classes Person name age gender eat walk Student Doctor Teacher ► Here, Person is an abstract class
  • 90. Example – Abstract Classes Vehicle color model accelerate applyBrakes Car Truck Bus ► Here, Vehicle is an abstract class
  • 91. Concrete Classes ►A concrete class implements a concrete concept ► Main purpose is to be instantiated ► Provides implementation details specific to the domain context
  • 92. Example – Concrete Classes Person Student Doctor program Teacher studyYear study heldExam ► Here,Student, Teacher and Doctor are concrete classes
  • 93. Example – Concrete Classes Vehicle Car Truck Bus capacity load unload • Here, Car, Bus and Truck are concrete classes
  • 94. Object oriented programming (OOP) Lecture No. 7
  • 95. Class ► Class is a tool to realize objects ► Class is a tool for defining a new type
  • 96. Example ► Lionis an object ► Student is an object ► Both has some attributes and some behaviors
  • 97. Uses ► The problem becomes easy to understand ► Interactions can be easily modeled
  • 98. Type in C++ ► Mechanism for user defined types are  Structures  Classes ► Built-in types are like int, float and double ► User defined type can be  Student in student management system  Circle in a drawing software
  • 99. Abstraction ► Only include details in the system that are required for making a functional system ► Student  Name Relevant to our problem  Address  Sibling Not relevant to our problem  Father Business
  • 100. Defining a New User Defined Type class ClassName { Syntax … DataType MemberVariable; ReturnType MemberFunction(); … }; Syntax
  • 101. Example class Student { int rollNo; char *name; Member variables float CGPA; Member Functions char *address; … void setName(char *newName); void setRollNo(int newRollNo); … };
  • 102. Why Member Function ► They model the behaviors of an object ► Objects can make their data invisible ► Object remains in consistent state
  • 103. Example Student aStudent; aStudent.rollNo = 514; aStudent.rollNo = -514; //Error
  • 104. Object and Class ► Objectis an instantiation of a user defined type or a class
  • 105. Declaring class variables ► Variables of classes (objects) are declared just like variables of structures and built-in data types TypeName VaraibaleName; int var; Student aStudent;
  • 106. Accessing members ► Members of an object can be accessed using  dot operator (.) to access via the variable name  arrow operator (->) to access via a pointer to an object ► Member variables and member functions are accessed in a similar fashion
  • 107. Example class Student{ int rollNo; void setRollNo(int aNo); }; Student aStudent; Error aStudent.rollNo;
  • 109. Access specifiers ► There are three access specifiers  ‘public’ is used to tell that member can be accessed whenever you have access to the object  ‘private’ is used to tell that member can only be accessed from a member function  ‘protected’ to be discussed when we cover inheritance
  • 110. Example class Student{ private: char * name; Cannot be accessed outside class int rollNo; public: void setName(char *); Can be accessed void setRollNo(int); outside class ... };
  • 111. Example class Student{ ... int rollNo; public: void setRollNo(int aNo); }; int main(){ Student aStudent; aStudent.SetRollNo(1); }
  • 112. Default access specifiers ► When no access specifier is mentioned then by default the member is considered private member
  • 113. Example class Student class Student { { char * name; private: int RollNo; char * name; }; int RollNo; };
  • 114. Example class Student { char * name; int RollNo; void SetName(char *); }; Error Student aStudent; aStudent.SetName(Ali);
  • 115. Example class Student { char * name; int RollNo; public: void setName(char *); }; Student aStudent; aStudent.SetName(“Ali”);

Hinweis der Redaktion

  1. class is a keyword and must always be in small caps Omitting the semicolon at the end is a syntax error 13:22
  2. Accessing a private member from outside member function is a syntax error You can use access specifiers as many times as you like Each access specifier must be followed by a ‘:’