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► ...
Course Contents► Object-Orientation► Objects and Classes► Overloading► Inheritance► Polymorphism► Generic Programming► Exc...
Books► C++   How to Program  By Deitel & Deitel► The   C++ Programming Language  By Bjarne Stroustrup► Object-Oriented    ...
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                   Hous...
Object-Orientation - Advantages► People   think in terms of objects► OO   models map to reality► Therefore,   OO models ar...
What is an Object?An object is► Something    tangible (Ali, Car)► Something   that can be apprehended intellectually (Time...
… 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► I...
Example – Car is a Tangible Object► State   (attributes)  - Color  - Model► behaviour   (operations)  - Accelerate        ...
Example – Time is an Object      Apprehended Intellectually► State   (attributes)  - Hours                - Seconds  - Min...
Example – Date is an Object        Apprehended Intellectually► State   (attributes)  -   Year               - Day  -   Mon...
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 mani...
Example – Information Hiding► Ali’s   name is stored within his brain► We      can’t access his name directly► Rather     ...
Example – Information Hiding►A   phone stores several phone numbers► Wecan’t read the numbers directly from the SIM card► ...
Information Hiding                 Advantages► Simplifies          the model by hiding  implementation details► It   is a ...
Encapsulation► Data and behaviour are tightly coupled inside an object► Boththe information structure and implementation d...
Example – Encapsulation► Alistores his personal information and  knows how to translate it to the desired  language► We   ...
Example – Encapsulation►A Phone stores phone numbers in digital format and knows how to convert it into human-readable cha...
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...
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► Upda...
Implementation► Provides   services offered by the object interface► This   includes   Data structures to hold object sta...
Example – Implementation of            Gear Box► Data   Structure   Mechanical structure of gear box► Functionality   Me...
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...
Example – Separation of     Interface & Implementation►A driver can drive a car independent of engine type (petrol, diesel...
Example – Separation of     Interface & Implementation►A driver can apply brakes independent of brakes type (simple, disk)...
Advantages of Separation► Users need not to worry about a change until the interface is same► Low   Complexity► Directacce...
Messages► Objects  communicate through messages► They send messages (stimuli) by invoking  appropriate operations on the t...
Examples – Messages►A Person sends message (stimulus) “stop” to a Car by applying brakes►A Person sends message “place cal...
Object-Oriented Programming           (OOP)        Lecture No. 3
Abstraction► Abstraction   is a way to cope with  complexity.► Principle   of abstraction: “Capture only those details abo...
Example – Abstraction Ali is a PhD student and teaches BS students► Attributes  -   Name                   -   Employee ID...
Example – Abstraction Ali is a PhD student and teaches BS students► behaviour  -   Study             -   DevelopExam  -   ...
Example – Abstraction               Student’s Perspective► Attributes  -   Name                      -   Employee ID  -   ...
Example – Abstraction               Student’s Perspective► behaviour  -   Study                -   DevelopExam  -   GiveEx...
Example – Abstraction               Teacher’s Perspective► Attributes  -   Name                     -   Employee ID  -   S...
Example – Abstraction               Teacher’s Perspective► behaviour  -   Study                -   DevelopExam  -   GiveEx...
Example – Abstraction   A cat can be viewed with different   perspectives► Ordinary   Perspective   ► Surgeon’s   Perspect...
Example – Abstraction                         Engineer’s ViewDriver’s View
Abstraction – Advantages► Simplifies   the model by hiding irrelevant  details► Abstraction            provides the freedo...
Classes► Inan OO model, some of the objects exhibit identical characteristics (information structure and behaviour)► We   ...
Example – Class► Ali    studies mathematics► Anam studies physics► Sohail studies chemistry► Each one is a Student► We say...
Example – Class► Ahsan   teaches mathematics► Aamir teaches computer science► Atif teaches physics► Each one is a teacher►...
Graphical Representation of Classes  (Class Name)                     (Class Name)  (attributes)                      Supp...
Example – Graphical Representation            of Classes     Circle   center              Circle   radius   draw          ...
Example – Graphical Representation            of Classes     Person    name              Person    age    gender          ...
Inheritance►A   child inherits characteristics of its parents► Besides        inherited characteristics, a child may have ...
Inheritance in Classes► If a class B inherits from class A then it  contains all the characteristics (information  structu...
Example – Inheritance          PersonStudent             Doctor          Teacher
Example – Inheritance       ShapeLine             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    ...
Example – “IS A” Relationship                 Shape                color                coord                draw         ...
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 c...
Example Reuse                    Shape                   color                   coord                   draw             ...
Example Reuse                 Person               name               age               gender               eat          ...
Example Reuse                 Person               name               age               gender               eat          ...
Object-Oriented Programming           (OOP)        Lecture No. 4
Recap – Inheritance► Derivedclass inherits all the characteristics of the base class► Besidesinherited characteristics, de...
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 a...
Example – Generalization    Linecolorvertices        Circlelength       colormove         vertices        TrianglesetColor...
Example – Generalization                 Shape                color                vertices                move           ...
Example – Generalization  Studentnameage           Teachergender      name                             Doctorprogram     a...
Example – Generalization               Person             name             age             gender             eat         ...
Sub-typing & Specialization► We want to add a new class to an existing  model► Find an existing class that already  implem...
Sub-typing (Extension)► Sub-typingmeans that derived class is behaviourally compatible with the base class► Behaviourallyc...
Person              name              age              gender              eats Example –    walksSub-typing(Extension)   ...
Shape               color               vertices               setColor Example –     moveSub-typing(Extension)           ...
Specialization (Restriction)► Specialization               means that derived class is behaviourally incompatible with the...
Example – Specialization     (Restriction)    Personage : [0..100]…setAge( a )        age = a…     Adult        If age < 1...
Example – Specialization     (Restriction)  IntegerSet…add( elem )    add element…              to the set               I...
Overriding►A class may need to override the default behaviour provided by its base class► Reasons    for overriding     P...
Example – Specific Behaviour                 Shape                color                vertices                draw       ...
Example – Extension Window width height open close drawDialogBox       1- Invoke Window’scontrols            drawenable   ...
Example – Restriction  IntegerSet…add( elem )    Add element…              to the set               If elem < 1 then  Natu...
Example – Improve Performance                               Shape                              color► Class Circle overrid...
Abstract Classes► An  abstract class implements an abstract  concept► Main purpose is to be inherited by other  classes► C...
Example – Abstract Classes                    Person                   name                   age                   gender...
Example – Abstract Classes                    Vehicle                  color                  model                  accel...
Concrete Classes►A concrete class implements a concrete concept► Main   purpose is to be instantiated► Provides         im...
Example – Concrete Classes                  Person     Student                   Doctor  program         Teacher  studyYea...
Example – Concrete Classes               Vehicle     Car                       Truck                 Bus                  ...
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, floa...
Abstraction► Only include details in the system that are  required for making a functional system► Student     Name      ...
Defining a New User Defined Typeclass ClassName{            Syntax  …  DataType MemberVariable;  ReturnType MemberFunction...
Exampleclass Student{  int rollNo;  char *name;       Member variables  float CGPA;                                       ...
Why Member Function► They model the behaviors of an object► Objects can make their data invisible► Object remains in consi...
ExampleStudent 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...
Accessing members► Members   of an object can be accessed using   dot operator (.) to access via the variable name   arr...
Exampleclass 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...
Exampleclass Student{private:  char * name;                  Cannot be accessed outside class  int rollNo;public:  void se...
Exampleclass Student{...  int rollNo;public:  void setRollNo(int aNo);};int main(){  Student aStudent;  aStudent.SetRollNo...
Default access specifiers► When no access specifier is mentioned then by default the member is considered private member
Exampleclass Student         class Student{                     {  char * name;        private:  int RollNo;           cha...
Exampleclass Student{  char * name;  int RollNo;  void SetName(char *);};                        ErrorStudent aStudent;aSt...
Exampleclass Student{  char * name;  int RollNo;public:  void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);
Upcoming SlideShare
Loading in …5
×

Lecture01

719 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
719
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
31
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • class is a keyword and must always be in small caps Omitting the semicolon at the end is a syntax error 13:22
  • 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 ‘:’
  • Lecture01

    1. 1. Object-Oriented Programming (OOP) Lecture No. 1
    2. 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. 3. Course Contents► Object-Orientation► Objects and Classes► Overloading► Inheritance► Polymorphism► Generic Programming► Exception Handling► Introduction to Design Patterns
    4. 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
    5. 5. Object-Orientation (OO)
    6. 6. What is Object-Orientation?►A technique for system modeling► OO model consists of several interacting objects
    7. 7. What is a Model?►A model is an abstraction of something► Purposeis to understand the product before developing it
    8. 8. Examples – Model► Highway maps► Architectural models► Mechanical models
    9. 9. Example – OO Model
    10. 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. 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. 12. What is an Object?An object is► Something tangible (Ali, Car)► Something that can be apprehended intellectually (Time, Date)
    13. 13. … What is an Object?An object has► State (attributes)► Well-defined behaviour (operations)► Unique identity
    14. 14. Example – Ali is a Tangible Object► State (attributes)  Name  Age► behaviour (operations)  Walks  Eats► Identity  His name
    15. 15. Example – Car is a Tangible Object► State (attributes) - Color - Model► behaviour (operations) - Accelerate - Start Car - Change Gear► Identity - Its registration number
    16. 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. 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. 18. Object-Oriented Programming (OOP) Lecture No. 2
    19. 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. 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. 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. 22. Information Hiding Advantages► Simplifies the model by hiding implementation details► It is a barrier against change propagation
    23. 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. 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. 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. 26. Encapsulation – Advantages► Simplicity and clarity► Low complexity► Better understanding
    27. 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. 28. Example – Interface of a Car► Steer Wheels► Accelerate► Change Gear► Apply Brakes► Turn Lights On/Off
    29. 29. Example – Interface of a Phone► Input Number► Place Call► Disconnect Call► Add number to address book► Remove number► Update number
    30. 30. Implementation► Provides services offered by the object interface► This includes  Data structures to hold object state  Functionality that provides required services
    31. 31. Example – Implementation of Gear Box► Data Structure  Mechanical structure of gear box► Functionality  Mechanism to change gear
    32. 32. Example – Implementation of Address Book in a Phone► Data Structure  SIM card► Functionality  Read/write circuitry
    33. 33. Separation of Interface & Implementation► Means change in implementation does not effect object interface► Thisis achieved via principles of information hiding and encapsulation
    34. 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. 35. Example – Separation of Interface & Implementation►A driver can apply brakes independent of brakes type (simple, disk)► Again, reason is the same interface
    36. 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. 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. 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. 39. Object-Oriented Programming (OOP) Lecture No. 3
    40. 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. 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. 42. Example – Abstraction Ali is a PhD student and teaches BS students► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
    43. 43. Example – Abstraction Student’s Perspective► Attributes - Name - Employee ID - Student Roll No - Designation - Year of Study - Salary - CGPA - Age
    44. 44. Example – Abstraction Student’s Perspective► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
    45. 45. Example – Abstraction Teacher’s Perspective► Attributes - Name - Employee ID - Student Roll No - Designation - Year of Study - Salary - CGPA - Age
    46. 46. Example – Abstraction Teacher’s Perspective► behaviour - Study - DevelopExam - GiveExam - TakeExam - PlaySports - Eat - DeliverLecture - Walk
    47. 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. 48. Example – Abstraction Engineer’s ViewDriver’s View
    49. 49. Abstraction – Advantages► Simplifies the model by hiding irrelevant details► Abstraction provides the freedom to defer implementation decisions by avoiding commitment to details
    50. 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. 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. 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. 53. Graphical Representation of Classes (Class Name) (Class Name) (attributes) Suppressed (operations) Form Normal Form
    54. 54. Example – Graphical Representation of Classes Circle center Circle radius draw Suppressed computeArea Form Normal Form
    55. 55. Example – Graphical Representation of Classes Person name Person age gender Suppressed eat Form walk Normal Form
    56. 56. Inheritance►A child inherits characteristics of its parents► Besides inherited characteristics, a child may have its own unique characteristics
    57. 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. 58. Example – Inheritance PersonStudent Doctor Teacher
    59. 59. Example – Inheritance ShapeLine Triangle Circle
    60. 60. Inheritance – “IS A” or “IS A KIND OF” Relationship► Eachderived class is a special kind of its base class
    61. 61. Example – “IS A” Relationship Person name age gender eat walk Student Teacher Doctorprogram designation designationstudyYear salary salarystudy teach checkUpheldExam takeExam prescribe
    62. 62. Example – “IS A” Relationship Shape color coord draw rotate setColor Circle Triangleradius Line angledraw length drawcomputeArea draw computeArea
    63. 63. Inheritance – Advantages► Reuse► Less redundancy► Increased maintainability
    64. 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. 65. Example Reuse Shape color coord draw rotate setColor Circle Triangleradius Line angledraw length drawcomputeArea draw computeArea
    66. 66. Example Reuse Person name age gender eat walk Student Teacher Doctorprogram designation designationstudyYear salary salarystudy teach checkUpheldExam takeExam prescribe
    67. 67. Example Reuse Person name age gender eat walk Student Teacher Doctorprogram designation designationstudyYear salary salarystudy teach checkUpheldExam takeExam prescribe
    68. 68. Object-Oriented Programming (OOP) Lecture No. 4
    69. 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. 70. Concepts Related with Inheritance► Generalization► Subtyping (extension)► Specialization (restriction)
    71. 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. 72. Example – Generalization Linecolorvertices Circlelength colormove vertices TrianglesetColor radius colorgetLength move vertices setColor angle computeArea move setColor computeArea
    73. 73. Example – Generalization Shape color vertices move setColor Circle Triangleradius Line anglecomputeArea length computeArea getLength
    74. 74. Example – Generalization Studentnameage Teachergender name Doctorprogram age namestudyYear gender agestudy designation genderheldExam salary designationeat teach salarywalk takeExam eat checkUp walk prescribe eat walk
    75. 75. Example – Generalization Person name age gender eat walk Student Teacher Doctorprogram designation designationstudyYear salary salarystudy teach checkUpheldExam takeExam prescribe
    76. 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. 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. 78. Person name age gender eats Example – walksSub-typing(Extension) Student program studyYear study takeExam
    79. 79. Shape color vertices setColor Example – moveSub-typing(Extension) Circle radius computeCF computeArea
    80. 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. 81. Example – Specialization (Restriction) Personage : [0..100]…setAge( a ) age = a… Adult If age < 18 thenage : [18..100] error… elsesetAge( a ) age = a…
    82. 82. Example – Specialization (Restriction) IntegerSet…add( elem ) add element… to the set If elem < 1 then NaturalSet error… elseadd( elem ) add element… to the set
    83. 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. 84. Example – Specific Behaviour Shape color vertices draw move setColor Circle Triangleradius Line angledraw length drawcomputeArea draw computeArea
    85. 85. Example – Extension Window width height open close drawDialogBox 1- Invoke Window’scontrols drawenable 2- draw the dialogdraw box
    86. 86. Example – Restriction IntegerSet…add( elem ) Add element… to the set If elem < 1 then NaturalSet give error… elseadd( elem ) Add element… to the set
    87. 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. 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. 89. Example – Abstract Classes Person name age gender eat walk Student Doctor Teacher► Here, Person is an abstract class
    90. 90. Example – Abstract Classes Vehicle color model accelerate applyBrakes Car Truck Bus► Here, Vehicle is an abstract class
    91. 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. 92. Example – Concrete Classes Person Student Doctor program Teacher studyYear study heldExam► Here,Student, Teacher and Doctor are concrete classes
    93. 93. Example – Concrete Classes Vehicle Car Truck Bus capacity load unload• Here, Car, Bus and Truck are concrete classes
    94. 94. Object oriented programming (OOP) Lecture No. 7
    95. 95. Class► Class is a tool to realize objects► Class is a tool for defining a new type
    96. 96. Example► Lionis an object► Student is an object► Both has some attributes and some behaviors
    97. 97. Uses► The problem becomes easy to understand► Interactions can be easily modeled
    98. 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. 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. 100. Defining a New User Defined Typeclass ClassName{ Syntax … DataType MemberVariable; ReturnType MemberFunction(); …}; Syntax
    101. 101. Exampleclass Student{ int rollNo; char *name; Member variables float CGPA; Member Functions char *address;… void setName(char *newName); void setRollNo(int newRollNo);…};
    102. 102. Why Member Function► They model the behaviors of an object► Objects can make their data invisible► Object remains in consistent state
    103. 103. ExampleStudent aStudent;aStudent.rollNo = 514;aStudent.rollNo = -514; //Error
    104. 104. Object and Class► Objectis an instantiation of a user defined type or a class
    105. 105. Declaring class variables► Variables of classes (objects) are declared just like variables of structures and built-in data typesTypeName VaraibaleName;int var;Student aStudent;
    106. 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. 107. Exampleclass Student{ int rollNo; void setRollNo(int aNo);}; Student aStudent; Error aStudent.rollNo;
    108. 108. Access specifiers
    109. 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. 110. Exampleclass Student{private: char * name; Cannot be accessed outside class int rollNo;public: void setName(char *); Can be accessed void setRollNo(int); outside class...};
    111. 111. Exampleclass Student{... int rollNo;public: void setRollNo(int aNo);};int main(){ Student aStudent; aStudent.SetRollNo(1);}
    112. 112. Default access specifiers► When no access specifier is mentioned then by default the member is considered private member
    113. 113. Exampleclass Student class Student{ { char * name; private: int RollNo; char * name;}; int RollNo; };
    114. 114. Exampleclass Student{ char * name; int RollNo; void SetName(char *);}; ErrorStudent aStudent;aStudent.SetName(Ali);
    115. 115. Exampleclass Student{ char * name; int RollNo;public: void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);

    ×