SlideShare una empresa de Scribd logo
1 de 27
Object Oriented Programming

Lecture 10 – Objects and Classes
        Robert Lafore, 3rd ed., Chapter 6



           Engr. M. Anwar-ul-Haq
Simple Class
#include <iostream>
using namespace std;

class smallobj                       //declare a class
{
   private:
     int somedata;

     public:
       void setdata (int d)     //member function to set data
       {
                somedata = d;
       }
     void showdata()            //member function to display data
     {
       cout << “Data is ” << somedata << endl;
     }
};                   OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                           2
Simple Class
int main()
{
    smallobj s1, s2;
    s1.setdata(1066);
    s2.setdata(1776);
    s1.showdata();
    s2.showdata();
    return 0;
}

               OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                     3
Objects and Classes
• The class smallobj declared in this program contains one
  data item and two member functions. The two member
  functions provide the only access to the data item from
  outside the class.

• The first member function sets the data item to a value,
  and the second displays the value.

• Placing data and functions together into a single entity is
  the central idea of object–oriented programming.

               OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                     4
Objects and Classes




 OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                       5
Instances
• An object is said to be an instance of a
  class, in the same way a type of car is an
  instance of a vehicle.

• Later, in main(), we define two objects—s1
  and s2—that are instances of that class.


            OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                  6
Class declaration
• The declaration starts with the keyword
  class, followed by the class name—smallobj
  in this case.

• Like a structure, the body of the class is
  delimited by braces and terminated by a
  semicolon.

            OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                  7
Private and Public
• A key feature of object–oriented programming is data
  hiding.

• Data is concealed within a class, so that it cannot be
  accessed mistakenly by functions outside the class.

• The primary mechanism for hiding data is to put it in a
  class and make it private. Private data or functions can
  only be accessed from within the class. Public data or
  functions, on the other hand, are accessible from outside
  the class.


               OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                     8
Private and Public




OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                      9
Data Hiding
• To provide a security measure you might, for example,
  require a user to supply a password before granting access
  to a database. The password is meant to keep unauthorized
  or malevolent users from altering (or often even reading)
  the data.

• Data hiding, on the other hand, means hiding data from
  parts of the program that don’t need to access it. More
  specifically, one class’s data is hidden from other classes.
  Data hiding is designed to protect well– intentioned
  programmers from honest mistakes. Programmers who
  really want to can figure out a way to access private data,
  but they will find it hard to do so by accident.
               OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                    10
Member functions
• Member functions are functions that are included
  within a class.

• There are two member functions in smallobj:
  setdata() and showdata().

• setdata() and showdata() follow the keyword
  public, they can be accessed from outside the
  class.
             OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                  11
Class specifier syntax




  OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                       12
Objects
• The declaration for the class smallobj does not
  create any objects. It only describes how they will
  look when they are created, just as a structure
  declaration describes how a structure will look but
  doesn’t create any structure variables.

• It is the definition that actually creates objects that
  can be used by the program. Defining an object is
  similar to defining a variable of any data type:
  Space is set aside for it in memory.
              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   13
Instantiation
• Defining objects in this way means creating
  them. This is also called instantiating them.

• The term instantiating arises because an
  instance of the class is created. An object is
  an instance (that is, a specific example) of a
  class. Objects are sometimes called instance
  variables.

            OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                 14
Member function
• s1.setdata(1066);

• This syntax is used to call a member function that
  is associated with a specific object.

• Because setdata() is a member function of the
  smallobj class, it must always be called in
  connection with an object of this class.

             OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                  15
Member function
• To use a member function, the dot operator
  (the period) connects the object name and
  the member function.

• The dot operator is also called the class
  member access operator.)


            OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                 16
Example
#include <iostream>
using namespace std;
class part
{
    private:
         int modelnumber;             //ID number of widget
         int partnumber;              //ID number of widget part
         float cost;                   //cost of part
     public:

     void setpart(int mn, int pn, float c)        //set data
     {
         modelnumber = mn;
         partnumber = pn;
         cost = c;
     }

         void showpart()                        //display data
         {
               cout << “Model ” << modelnumber;
               cout << “, part ” << partnumber;
               cout << “, costs $” << cost << endl;
         }
                            OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                                 17
};
Example
int main()
{
    part part1;
    part1.setpart(6244, 373, 217.55F);
    part1.showpart(); //call member function
    return 0;
}
              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   18
Constructors
• Sometimes, it’s convenient if an object can
  initialize itself when it’s first created, without the
  need to make a separate call to a member function.
  Automatic initialization is carried out using a
  special member function called a constructor.

• A constructor is a member function that is
  executed automatically whenever an object is
  created.
              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   19
Constructor Example
• A counter is a variable that counts things.
  Maybe it counts file accesses, or the number
  of times the user presses the [Enter] key, or
  the number of customers entering a bank.

• Each time such an event takes place, the
  counter is incremented (1 is added to it).
  The counter can also be accessed to find the
  current count.
           OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                20
Constructor
class Counter                              int main()
{                                          {
   private:                                Counter c1, c2;
         unsigned int count;               cout << “nc1=” << c1.get_count();
   public:                                 cout << “nc2=” << c2.get_count();
         Counter() : count(0)              c1.inc_count();
         { /*empty body*/ }                c2.inc_count();
                                           c2.inc_count();
        void inc_count()
        { count++; }                       cout << “nc1=” << c1.get_count();
                                           cout << “nc2=” << c2.get_count();
        int get_count()
        { return count; }                  Return
};                                         }
                      OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                           21
Constructor
• When an object of type Counter is first created, we
  want its count to be initialized to 0. After all, most
  counts start at 0.

• We could provide a set_count() function to do this
  and call it with an argument of 0, or we could
  provide a zero_count() function, which would
  always set count to 0. However, such functions
  would need to be executed every time we created a
  Counter object.
              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   22
Constructor
• Counter c1; //every time we do this,
• c1.zero_count(); //we must do this too
• This is mistake prone, because the programmer
  may forget to initialize the object after creating it.
• It’s more reliable and convenient, especially when
  there are a great many objects of a given class, to
  cause each object to initialize itself when it’s
  created.

              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   23
Constructor
• Thus in main(), the statement Counter c1, c2;
  creates two objects of type Counter. As each is
  created, its constructor, Counter(), is executed.

• This function sets the count variable to 0. So the
  effect of this single statement is to not only create
  two objects, but also to initialize their count
  variables to 0.

              OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                   24
Constructor Properties
• They have exactly the same name (Counter
  in this example) as the class of which they
  are members.

• No return type is used for constructors.



           OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                25
Constructor - Initializer list
count()
{ count = 0; }


This is not the preferred approach (although it does
 work).
count() : count(0)
{}

If multiple members must be initialized, they’re separated
    by commas.
           OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                                26
Constructor - Initializer list
someClass() : m1(7), m2(33), m2(4)
{}

– Members initialized in the initializer list are
  given a value before the constructor even starts
  to execute. This is important in some situations.
– For example, the initializer list is the only way
  to initialize const member data and references.

          OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi
                                                                               27

Más contenido relacionado

La actualidad más candente

Inter - thread communication
Inter - thread communicationInter - thread communication
Inter - thread communicationBhumikaDhingra3
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Object Oriented Programming Principles
Object Oriented Programming PrinciplesObject Oriented Programming Principles
Object Oriented Programming PrinciplesAndrew Ferlitsch
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiersKhaled Adnan
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Asfand Hassan
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software EngineeringManish Kumar
 
Object oriented programming interview questions
Object oriented programming interview questionsObject oriented programming interview questions
Object oriented programming interview questionsKeet Sugathadasa
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
The Object Model
The Object Model  The Object Model
The Object Model yndaravind
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming Rokonuzzaman Rony
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS ConceptBoopathi K
 

La actualidad más candente (20)

Inter - thread communication
Inter - thread communicationInter - thread communication
Inter - thread communication
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Oops
OopsOops
Oops
 
Object Oriented Programming Principles
Object Oriented Programming PrinciplesObject Oriented Programming Principles
Object Oriented Programming Principles
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software Engineering
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Object oriented programming interview questions
Object oriented programming interview questionsObject oriented programming interview questions
Object oriented programming interview questions
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Compare between pop and oop
Compare between pop and oopCompare between pop and oop
Compare between pop and oop
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
The Object Model
The Object Model  The Object Model
The Object Model
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 

Similar a oop Lecture 10

Similar a oop Lecture 10 (20)

oop Lecture 11
oop Lecture 11oop Lecture 11
oop Lecture 11
 
oop Lecture 16
oop Lecture 16oop Lecture 16
oop Lecture 16
 
Oop lec 2
Oop lec 2Oop lec 2
Oop lec 2
 
oop Lecture 7
oop Lecture 7oop Lecture 7
oop Lecture 7
 
oop Lecture19
oop Lecture19oop Lecture19
oop Lecture19
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1
 
Oops
OopsOops
Oops
 
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
CS3391 -OOP -UNIT – I  NOTES FINAL.pdfCS3391 -OOP -UNIT – I  NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdfSulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptx
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core java
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
MCA NOTES.pdf
MCA NOTES.pdfMCA NOTES.pdf
MCA NOTES.pdf
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
 
Ah java-ppt2
Ah java-ppt2Ah java-ppt2
Ah java-ppt2
 

Más de Anwar Ul Haq

Más de Anwar Ul Haq (6)

oop Lecture 17
oop Lecture 17oop Lecture 17
oop Lecture 17
 
oop Lecture 9
oop Lecture 9oop Lecture 9
oop Lecture 9
 
oop Lecture 6
oop Lecture 6oop Lecture 6
oop Lecture 6
 
oop Lecture 5
oop Lecture 5oop Lecture 5
oop Lecture 5
 
oop Lecture 4
oop Lecture 4oop Lecture 4
oop Lecture 4
 
oop Lecture 3
oop Lecture 3oop Lecture 3
oop Lecture 3
 

Último

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
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
 

Último (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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
 

oop Lecture 10

  • 1. Object Oriented Programming Lecture 10 – Objects and Classes Robert Lafore, 3rd ed., Chapter 6 Engr. M. Anwar-ul-Haq
  • 2. Simple Class #include <iostream> using namespace std; class smallobj //declare a class { private: int somedata; public: void setdata (int d) //member function to set data { somedata = d; } void showdata() //member function to display data { cout << “Data is ” << somedata << endl; } }; OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 2
  • 3. Simple Class int main() { smallobj s1, s2; s1.setdata(1066); s2.setdata(1776); s1.showdata(); s2.showdata(); return 0; } OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 3
  • 4. Objects and Classes • The class smallobj declared in this program contains one data item and two member functions. The two member functions provide the only access to the data item from outside the class. • The first member function sets the data item to a value, and the second displays the value. • Placing data and functions together into a single entity is the central idea of object–oriented programming. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 4
  • 5. Objects and Classes OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 5
  • 6. Instances • An object is said to be an instance of a class, in the same way a type of car is an instance of a vehicle. • Later, in main(), we define two objects—s1 and s2—that are instances of that class. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 6
  • 7. Class declaration • The declaration starts with the keyword class, followed by the class name—smallobj in this case. • Like a structure, the body of the class is delimited by braces and terminated by a semicolon. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 7
  • 8. Private and Public • A key feature of object–oriented programming is data hiding. • Data is concealed within a class, so that it cannot be accessed mistakenly by functions outside the class. • The primary mechanism for hiding data is to put it in a class and make it private. Private data or functions can only be accessed from within the class. Public data or functions, on the other hand, are accessible from outside the class. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 8
  • 9. Private and Public OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 9
  • 10. Data Hiding • To provide a security measure you might, for example, require a user to supply a password before granting access to a database. The password is meant to keep unauthorized or malevolent users from altering (or often even reading) the data. • Data hiding, on the other hand, means hiding data from parts of the program that don’t need to access it. More specifically, one class’s data is hidden from other classes. Data hiding is designed to protect well– intentioned programmers from honest mistakes. Programmers who really want to can figure out a way to access private data, but they will find it hard to do so by accident. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 10
  • 11. Member functions • Member functions are functions that are included within a class. • There are two member functions in smallobj: setdata() and showdata(). • setdata() and showdata() follow the keyword public, they can be accessed from outside the class. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 11
  • 12. Class specifier syntax OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 12
  • 13. Objects • The declaration for the class smallobj does not create any objects. It only describes how they will look when they are created, just as a structure declaration describes how a structure will look but doesn’t create any structure variables. • It is the definition that actually creates objects that can be used by the program. Defining an object is similar to defining a variable of any data type: Space is set aside for it in memory. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 13
  • 14. Instantiation • Defining objects in this way means creating them. This is also called instantiating them. • The term instantiating arises because an instance of the class is created. An object is an instance (that is, a specific example) of a class. Objects are sometimes called instance variables. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 14
  • 15. Member function • s1.setdata(1066); • This syntax is used to call a member function that is associated with a specific object. • Because setdata() is a member function of the smallobj class, it must always be called in connection with an object of this class. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 15
  • 16. Member function • To use a member function, the dot operator (the period) connects the object name and the member function. • The dot operator is also called the class member access operator.) OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 16
  • 17. Example #include <iostream> using namespace std; class part { private: int modelnumber; //ID number of widget int partnumber; //ID number of widget part float cost; //cost of part public: void setpart(int mn, int pn, float c) //set data { modelnumber = mn; partnumber = pn; cost = c; } void showpart() //display data { cout << “Model ” << modelnumber; cout << “, part ” << partnumber; cout << “, costs $” << cost << endl; } OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 17 };
  • 18. Example int main() { part part1; part1.setpart(6244, 373, 217.55F); part1.showpart(); //call member function return 0; } OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 18
  • 19. Constructors • Sometimes, it’s convenient if an object can initialize itself when it’s first created, without the need to make a separate call to a member function. Automatic initialization is carried out using a special member function called a constructor. • A constructor is a member function that is executed automatically whenever an object is created. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 19
  • 20. Constructor Example • A counter is a variable that counts things. Maybe it counts file accesses, or the number of times the user presses the [Enter] key, or the number of customers entering a bank. • Each time such an event takes place, the counter is incremented (1 is added to it). The counter can also be accessed to find the current count. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 20
  • 21. Constructor class Counter int main() { { private: Counter c1, c2; unsigned int count; cout << “nc1=” << c1.get_count(); public: cout << “nc2=” << c2.get_count(); Counter() : count(0) c1.inc_count(); { /*empty body*/ } c2.inc_count(); c2.inc_count(); void inc_count() { count++; } cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count(); int get_count() { return count; } Return }; } OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 21
  • 22. Constructor • When an object of type Counter is first created, we want its count to be initialized to 0. After all, most counts start at 0. • We could provide a set_count() function to do this and call it with an argument of 0, or we could provide a zero_count() function, which would always set count to 0. However, such functions would need to be executed every time we created a Counter object. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 22
  • 23. Constructor • Counter c1; //every time we do this, • c1.zero_count(); //we must do this too • This is mistake prone, because the programmer may forget to initialize the object after creating it. • It’s more reliable and convenient, especially when there are a great many objects of a given class, to cause each object to initialize itself when it’s created. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 23
  • 24. Constructor • Thus in main(), the statement Counter c1, c2; creates two objects of type Counter. As each is created, its constructor, Counter(), is executed. • This function sets the count variable to 0. So the effect of this single statement is to not only create two objects, but also to initialize their count variables to 0. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 24
  • 25. Constructor Properties • They have exactly the same name (Counter in this example) as the class of which they are members. • No return type is used for constructors. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 25
  • 26. Constructor - Initializer list count() { count = 0; } This is not the preferred approach (although it does work). count() : count(0) {} If multiple members must be initialized, they’re separated by commas. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 26
  • 27. Constructor - Initializer list someClass() : m1(7), m2(33), m2(4) {} – Members initialized in the initializer list are given a value before the constructor even starts to execute. This is important in some situations. – For example, the initializer list is the only way to initialize const member data and references. OOP Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Rawalpindi 27