SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS ConceptBoopathi K
 
Shell programming
Shell programmingShell programming
Shell programmingMoayad Moawiah
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
Command line arguments
Command line argumentsCommand line arguments
Command line argumentsAshok Raj
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesFellowBuddy.com
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)MD Sulaiman
 
java token
java tokenjava token
java tokenJadavsejal
 

Was ist angesagt? (20)

Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
String in java
String in javaString in java
String in java
 
Shell programming
Shell programmingShell programming
Shell programming
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java program structure
Java program structure Java program structure
Java program structure
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
 
java token
java tokenjava token
java token
 

Ähnlich wie oop Lecture 10

oop Lecture 11
oop Lecture 11oop Lecture 11
oop Lecture 11Anwar Ul Haq
 
oop Lecture 16
oop Lecture 16oop Lecture 16
oop Lecture 16Anwar Ul Haq
 
oop Lecture 7
oop Lecture 7oop Lecture 7
oop Lecture 7Anwar Ul Haq
 
oop Lecture19
oop Lecture19oop Lecture19
oop Lecture19Anwar Ul Haq
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesBalamuruganV28
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Anwar Ul Haq
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
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.pdfSULTHAN BASHA
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptxPandeeswariKannan
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core javaAisha Siddiqui
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps conceptsNikhil Agrawal
 

Ähnlich wie 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
 

Mehr von Anwar Ul Haq

oop Lecture 17
oop Lecture 17oop Lecture 17
oop Lecture 17Anwar Ul Haq
 
oop Lecture 9
oop Lecture 9oop Lecture 9
oop Lecture 9Anwar Ul Haq
 
oop Lecture 6
oop Lecture 6oop Lecture 6
oop Lecture 6Anwar Ul Haq
 
oop Lecture 5
oop Lecture 5oop Lecture 5
oop Lecture 5Anwar Ul Haq
 
oop Lecture 4
oop Lecture 4oop Lecture 4
oop Lecture 4Anwar Ul Haq
 
oop Lecture 3
oop Lecture 3oop Lecture 3
oop Lecture 3Anwar Ul Haq
 

Mehr von 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
 

KĂźrzlich hochgeladen

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
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
 
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
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

KĂźrzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
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
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

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