SlideShare une entreprise Scribd logo
1  sur  38
Lecture 07



     Classes and Objects


Learn about:
i) Relationship between class and objects
ii) Data members & member functions
iii) Member access specifier: private & public
iv) Objects as physical and user defined data types


                                                      1
Class and Objects
• What is a class?
  – Class is a blue print or a prototype of OBJECT
  – Based on which any number of objects can be
    created.
  – EG : to build a new car
     • step 1 : create a prototype
     • step 2 : can build any number of cars based on the
                 prototype
           • All the cars will have the features of the prototype

   prototype                   Car1            Car2           Car3
                                                             2/15
How a class will look Like?


         Student             class name

         idnum
                               data members
         gpa

       setData
                              member functions
       showData


A class declaration describes a set of related data and associated
function which work on those data.
                                                         3/15
A Simple Class:
               Class Declaration (Option 1)
#include <iostream.h>
class Student     // class declaration
{                        can only be accessed within class
  private:
    int idNum =0;           //class data members
    double gpa = 0.0;
                        accessible from outside andwithin class
  public:
    void setData(int id, double result)
    { idNum = id;
      gpa = result; }
                                     Object1        Object2
     void showData()
       { cout << ”Student Id is ” << idNum << endl;
         cout << ”GPA is " << gpa << endl; }
};
                                                   4/15
A Simple Class:
               Class Declaration (Option 2)
#include <iostream.h>
class Student     // class declaration
{ private:                                   Explanation
     int idNum;          //class data
     double gpa;
   public:
     void setData(int, double) ;   scope resolution operator
     void showData();
};
// Implementation of member functions
void Student :: setData(int id, double result)
    { idNum = id;
      gpa = result; }
void Student :: showData()
      { cout << ”Student Id is ” << idNum << endl;
        cout << ”GPA is " << gpa << endl; }   5/15
Scope resolution
             Operator
• Operator ---> ::
• Definition : It tells the compiler the scope
               of the function
  –            The function belongs to which
                class
• Where it can be used?
  – A function can be written within a class or
    outside a class.
  – When written outside the class, the scope of
    the function should be defined. Example
                                          6/15
Scope resolution
          operator : Difference
Class xyz                  Class xyz
{ private:                 { private:
     int id; char grade;                int id; char
                           grade;
  public:                       public:
     void set ( )                     void set ( )
     { id = 10;            }
       grade = ‘A’;        void xyz::set ( )
                           { id = 10; grade = ‘A’;}
     }
};                                           7/15
A Simple Class:
          Object Definition and Manipulation
void main()                  objects’ creation or instantiation
{
   Student s1, s2;

    s1.setData(10016666, 3.14);
    s2.setData(10011776, 3.55);

    s1.showData();
    s2.showData();
                     accessing or invoking member functions
}                    Syntax:
                     object_name   . member_function_name
                        member access operator
                                                    8/15
A Simple Class:
Sending a message to an object
             1 . Through which objects
             interact with each other
Student:s1   2. Whom - object name
 idnum         action - method name
 gpa           parameters

setData              showData()
showData
                A C++ statement:
                s1.showData()
                                  9/15
A Simple Program:
                        How it works?
                    Student s1, s2;
CLASS:                          OBJECTS:

  Student                Student:s1          Student:s2
  int idnum;             int idnum;          int idnum;
  double gpa;            double gpa;         double gpa;
void setData(int,      void setData(int,   void setData(int,
double);               double);            double);
void showData();       void showData();    void showData();


                                                10/15
A Simple Program:
          How it works? What is the output ?

s1.setData(10016666, 3.14);   s2.setData(10011776, 3.55);
 s1.showData();               s2.showData();


        Student:s1                    Student:s2
       idnum 10016666                idnum 10011776

       gpa 3.14                      gpa 3.55

      void setData(int,             void setData(int,
      double);                      double);
      void showData();              void showData();
                                               11/15
A simple program example

#include <iostream.h>                      void main()
                                           {
class Student                                Student aStudent;
{
  private:
                                               aStudent.setIdNum(10019999);
   int idNum;
   char studName[20];
   double gpa;                                 aStudent.setName(‘Robbie’);

public:                                        aStudent.setGPA(3.57);
   void displayStudentData();
   void setIdNum(int);                         aStudent.displayStudentData();
   void setName(char[]);
   void setGPA(double);
                                           }
};

//Implementation - refer to notes page 2
(Lecture 7).                                                       12/15
A simple program example

#include <iostream.h>                             void main()
class Distance                                    {
{ private:                                          Distance dist1, dist2;
     int feet;                                      dist1.setDistance(11, 6.25);
     float inches;                                  dist2.getDistance();
 public:
   void setDistance(int ft, float in)                 //display lengths
   { feet = ft; inches = in; }                        cout << "ndist1 = ";
    void getDistancet()                               dist1.showDistance();
   { cout << "nEnter feet: ";      cin>>feet;        cout << endl;
     cout << "Enter inches: "; cin>>inches;
    }                                                 cout << "ndist2 = ";
   void showDistance()                                dist2.showDistance();
   { cout << feet << "'-" << inches << '"'; }       cout << endl;
};                                                }
                                                                     13/15
UML - Unified Modeling Language



• UML are used for drawing models
  – Class diagram is one of the types of UML diagrams.
  – They Identify classes and their relationships
• How to draw class diagram?

            Car                                     Wheel
                           Association
      model                                    model
      color            1                     n width
      speed
      drive ( )                                 change ( )
      stop ( )                        More than 1
      turn( )          Multiplicity                      14/15
OOP Revisited

     1. Major benefit
         - close correspondence between the real-world things
    being modeled
    – Everything about a real-world thing is included in its class
      description. ( characteristics & behaviour )

•    This makes it easy to conceptualize a programming problem.
    You simply
    – figure out what parts of the problem can be most usefully
      represented as objects, and then
    – put all the data and functions connected with that object into the
      class.

• For small programs, you can often proceed by trial and error.

• For larger programs, you need to learn Object-Oriented Design
  (OOD) methodologies.
                                                           15/15
Write a program to add two numbers
         ( Unstructured Programming)


#include <iostream.h>
void main( )
{ int a,b,c;
cin >> a >> b;
c= a+b;
cout<<c;
c=a-b;
cout<<c;
}                                 16/15
Write a program to add two numbers
              (structured Programming)


#include <iostream.h>
                             void main( )
int a,b,c;                   {
input ( ){ cin>>a>>b;}        input( );
add()                         add( );
{ c= a+b; }                   print( );
                              sub( );
sub( )
                              print( );
{c= a-b;}                    }
print()
                                      17/15
{cout<<c;}
OOP
#include <iostream.h>
class sample
{
Private :                  void main( )
int a,b,c;                 {
Public:                     sample s;
input ( ){ cin>>a>>b;}     s.input( );
add()
                           s.add( );
{ c= a+b; }
                           s.print( );
sub( )
{c= a-b;}
                           s.sub( );
print()                    s.print( );
{cout<<c;}                 }
};                                        18/15
Constructors
                   and
               Destructors


Learn about:

i) Constructors
ii) Destructors
iii) When and how constructors & desctructors are
called?

                                                    19
What is a Constructor?


• A member function that is executed
  automatically each time an object is
  created.

• Must have exactly the same name as the
  class name.


• No return type is used for constructors.


• Purpose: Used to initialize the Data
  Members                    Example Next Slide
                                          20/15
Constructors: Definition

#include <iostream.h>
class Student    // class declaration
{ private:
    int idNum;          //class data
    double gpa;

  public:
    Student()
    {
      cout<<“An object of Student is created!!”<<endl;
    }

   void setData(int, double) ;
   void showData();
};
// Implementation of member functions
                                               21/15
Constructors: Definition

#include <iostream.h>
class Student    // class declaration
{   :
   public:
    Student()
    {
      cout<<“An object of Student is created!!”<<endl;
    }
    :
};
// Implementation of member functions

void main()
{     Student s1, s2;          Constructor is called twice!!
      :
}                            What is the output?
                                                   22/15
Types of Constructor?
• Two types : default & multi argument constructor
• A constructor without argument is called a default constructor.
• A constructor can be overloaded. Ie ( there can be another
  constructor with same name )

• One of the most common tasks a constructor does is to initialize
  data members. For example,           Student s1;
                                             Student:s1
       Student()                         idNum
                                         gpa     0
       {     idNum = 0;
                                               0.0
             gpa = 0.0;
       }                                     Student()
                                            setData();
                                            showData();
Initialize to default values.
                                                          23/15
Types of Constructor

• A multi-argument constructor can initialize data members to
  values passes as arguments. For example,

  Student(int num, double result)      Student s1(1001, 3.14);
      {     idNum = num;
                                               Student:s1
            gpa = result;
      }                                  idNum     1001

                                         gpa     3.14


                                             Student()
                                            setData();
Initialize with arguments                   showData();
passed to it                                            24/15
Default and overloaded Constructor:
                    A simple program example
#include <iostream.h>                       void main()
class Student                               {
{ private:                                    Student s1;
     int idNum;
                                              s1.setData(6666, 3.14);
    double gpa;

public:                                     Student s2(1776, 3.55);
  Student()                                  :
  { cout<<“An object is created”<<endl; }   } Student:s1          Student:s2

  Student(int id, double result)            idNum   6666         idNum   1776
  { idnum = id; gpa = result; }
                                            gpa 3.14             gpa 3.55
  void setData();
  void showData();
};                                           Student()              Student()
//Implementation - refer to notes page 3    setData();             setData();
(Lecture 8).                                showData();              25/15
                                                                  showData();
Constructor: Initializer list

• Preferred way of initializing the data members using constructors
  is as follows:
• Student(): idnum(0), gpa(0.0) { }
  Student(int id, double result):
  idnum(id), gpa(result) { }
  Counter() : count(0) { }
  SomeClass() : m1(7), m2(33), m3(4)
  { }
 Student( )                    Student ( int id,double result)
 { idnum = 0; gpa =0.0;}       { idnum = id; gpa = result;}
                                                      26/15
Constructor: Other Example

#include <iostream.h>                      void main()
                                           { Counter c1, c2;
class Counter
{ private:                                     cout << "nc1="<< c1.get_count();
         int count;                            cout << "nc2=" << c2.get_count();

     public:                                   c1.inc_count(); //increment c1
           Counter() : count(0)                c2.inc_count(); //increment c2
           { //empty body*}                    c2.inc_count(); //increment c2

       void inc_count()     { count++; }       cout << "nc1=" << c1.get_count();
       int get_count() { return count; }       cout << "nc2=" << c2.get_count();
};

                                                   What is the output?
// refer to page 4, Lecture 8              }
                                                                   27/15
What is a Destructor?


• A member function that is called
  automatically each time an object is
  destroyed.

• Has the same name as the constructor but
  is preceded by a tilde (~).


• No return type and take no arguments.
• Purpose : de-allocate the memory allotted
  for the data members
• EG :    class xyz { private : data members
                                        28/15
  public:
Destructor: Definition

#include <iostream.h>
class Student    // class declaration
{ private:
    int idNum;          //class data
    double gpa;

  public:
    ~Student()
    {
      cout<<“An object has been destroyed!!”<<endl;
    }

   void setData(int, double) ;
   void showData();
};
// Implementation of member functions
                                               29/15
Constructors & Destructors: A
                      Simple Example
#include <iostream.h>                       void main()
                                            { Student s1, s2;
class Student                                }
{ private:
         int idNum;

     public:
       Student()
      { cout<<“Object created.”<<endl;}       Output:
                                              Object created.
      ~Student()                              Object created
      { cout<<“Object destroyed!”<<endl;}     Object destroyed!
};                                            Object destroyed!


// refer to page 6, Lecture 8
                                                                30/15
Constructors and Destructors:
            Global, Static and Local Objects
• Constructors for global objects are called when the program
begin execution. Destructors are called when program terminates.

• Constructors for automatic local objects are called when
execution reaches the point where the objects are defined.
Destructors are called when objects leave their scope.

• Constructors for statics objects are called only once when
execution reaches the point where the objects are defined.
Destructors are called when program terminates.


                                                     31/15
Global, Static and Local Objects

                       class Test
                       { private: int data;
                       public: Test (int value);
                               ~Test();
                       ...};

Test :: Test (int value)
{ data = value;
  cout<<“ Object”<<data<<“ constructor”; }

Test::~Test()
{ cout<<“Object”<,data<<“ destructor”<<endl;
                               At this level, first object invokes
Test first (1);
                               its constructor ( global )

                                              Cont… in the next slide
                                                             32/15
Global, Static and Local Objects

void main()
{ cout<<“ (global created before main)”<<endl;

  Test second(2);                                   second object invokes
  cout<<“ (local automatic created in main)”<<endl;        its constructor

  static Test third(3);                                    third object invokes
  cout<<“ (local static created in main)”<<endl;                 its constructor

  func();   // function func is invoked link
                                                          forth object invokes
  {  Test forth(4);
                                                          its constructor
      cout<<“ (local automatic crated in inner block in
main)”<<endl;          forth object invokes       second, sixth, third,
  }                    its destructor             and first object invokes
}                                                                  33/15
                                                  its destructor respectively
Global, Static and Local Objects

void func()
                                                         fifth object invokes
{ Test fifth(5);
                                                               its constructor
   cout<<“ (local automatic created in func)”<<endl;

    static Test sixth(3);                            sixth object invoke
    cout<<“ (local static created in func)”<<endl;   its constructor
}
                      fifth object invokes
                      its destructor




                                                                  34/15
Global, Static and Local Objects

Output:

Object 1 constructor   (global created before main)
Object 2 constructor   (local automatic created in main)
Object 3 constructor   (local static created in main)
Object 5 constructor   (local automatic created in func)
Object 6 constructor   (local static created in func)
Object 5 destructor
Object 4 constructor   (local automatic created in inner block in main)
Object 4 destructor
Object 2 destructor
Object 6 destructor
Object 3 destructor
Object 1 destructor                   Another example in the
                                      next slide
                                                               35/15
Global, Static and Local Objects

Test first (1)                                               First object invokes
void main()                                                  its constructor
{ cout<<“ (global created before main)”<<endl;

  Test second(2);                                   second object invokes
  cout<<“ (local automatic created in main)”<<endl;        its constructor

  static Test third(3);                                          third object invokes
  cout<<“ (local static created in main)”<<endl;                       its constructor

  func();   // function func is invoked, refer to slide 16
                                                        forth object invokes
  {  Test forth(4);
                                                        its constructor
      cout<<“ (local automatic crated in inner block in
main)”<<endl;
   }
  func();   //function func is invoked again                     36/15
}
Global, Static and Local Objects

void func()
                                                        fifth object invokes
{ Test fifth(5);
                                                              its constructor
   cout<<“ (local automatic created in func)”<<endl;

    static Test sixth(3);                            sixth object DOESN’T invok
    cout<<“ (local static created in func)”<<endl;   its constructor again
}
                      fifth object invokes
                      its destructor




                                                                 37/15
Global, Static and Local Objects

Output:

Object 1 constructor (global created before main)
Object 2 constructor (local automatic created in main)
Object 3 constructor (local static created in main)
Object 5 constructor (local automatic created in func)
Object 6 constructor (local static created in func)
Object 5 destructor
Object 4 constructor (local automatic created in inner block in main)
Object 4 destructor
Object 5 constructor (local automatic created in func)
          (local static created in func)
Object 5 destructor
Object 2 destructor
Object 6 destructor
Object 3 destructor
Object 1 destructor
                                                              38/15

Contenu connexe

Tendances (20)

Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
06 inheritance
06 inheritance06 inheritance
06 inheritance
 
OOP C++
OOP C++OOP C++
OOP C++
 
Lecture18
Lecture18Lecture18
Lecture18
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
11slide
11slide11slide
11slide
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
10slide
10slide10slide
10slide
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Oop03 6
Oop03 6Oop03 6
Oop03 6
 
Python advance
Python advancePython advance
Python advance
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
08slide
08slide08slide
08slide
 
Unit 4
Unit 4Unit 4
Unit 4
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 

En vedette (8)

Facebook經營觀察 0820
Facebook經營觀察 0820Facebook經營觀察 0820
Facebook經營觀察 0820
 
Lecture21
Lecture21Lecture21
Lecture21
 
Lecture10
Lecture10Lecture10
Lecture10
 
Springwood at music resonate
Springwood at music resonateSpringwood at music resonate
Springwood at music resonate
 
Lecture16
Lecture16Lecture16
Lecture16
 
Lecture20
Lecture20Lecture20
Lecture20
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture05
Lecture05Lecture05
Lecture05
 

Similaire à Lecture07

Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfrajaratna4
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.pptBArulmozhi
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
Declaring friend function with inline code
Declaring friend function with inline codeDeclaring friend function with inline code
Declaring friend function with inline codeRajeev Sharan
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 

Similaire à Lecture07 (20)

Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
02.adt
02.adt02.adt
02.adt
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Inheritance
InheritanceInheritance
Inheritance
 
Oops concept
Oops conceptOops concept
Oops concept
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
L10
L10L10
L10
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Test Engine
Test EngineTest Engine
Test Engine
 
Test Engine
Test EngineTest Engine
Test Engine
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
Declaring friend function with inline code
Declaring friend function with inline codeDeclaring friend function with inline code
Declaring friend function with inline code
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 

Plus de elearning_portal (6)

Lecture19
Lecture19Lecture19
Lecture19
 
Lecture06
Lecture06Lecture06
Lecture06
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture04
Lecture04Lecture04
Lecture04
 

Dernier

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Dernier (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Lecture07

  • 1. Lecture 07 Classes and Objects Learn about: i) Relationship between class and objects ii) Data members & member functions iii) Member access specifier: private & public iv) Objects as physical and user defined data types 1
  • 2. Class and Objects • What is a class? – Class is a blue print or a prototype of OBJECT – Based on which any number of objects can be created. – EG : to build a new car • step 1 : create a prototype • step 2 : can build any number of cars based on the prototype • All the cars will have the features of the prototype prototype Car1 Car2 Car3 2/15
  • 3. How a class will look Like? Student class name idnum data members gpa setData member functions showData A class declaration describes a set of related data and associated function which work on those data. 3/15
  • 4. A Simple Class: Class Declaration (Option 1) #include <iostream.h> class Student // class declaration { can only be accessed within class private: int idNum =0; //class data members double gpa = 0.0; accessible from outside andwithin class public: void setData(int id, double result) { idNum = id; gpa = result; } Object1 Object2 void showData() { cout << ”Student Id is ” << idNum << endl; cout << ”GPA is " << gpa << endl; } }; 4/15
  • 5. A Simple Class: Class Declaration (Option 2) #include <iostream.h> class Student // class declaration { private: Explanation int idNum; //class data double gpa; public: void setData(int, double) ; scope resolution operator void showData(); }; // Implementation of member functions void Student :: setData(int id, double result) { idNum = id; gpa = result; } void Student :: showData() { cout << ”Student Id is ” << idNum << endl; cout << ”GPA is " << gpa << endl; } 5/15
  • 6. Scope resolution Operator • Operator ---> :: • Definition : It tells the compiler the scope of the function – The function belongs to which class • Where it can be used? – A function can be written within a class or outside a class. – When written outside the class, the scope of the function should be defined. Example 6/15
  • 7. Scope resolution operator : Difference Class xyz Class xyz { private: { private: int id; char grade; int id; char grade; public: public: void set ( ) void set ( ) { id = 10; } grade = ‘A’; void xyz::set ( ) { id = 10; grade = ‘A’;} } }; 7/15
  • 8. A Simple Class: Object Definition and Manipulation void main() objects’ creation or instantiation { Student s1, s2; s1.setData(10016666, 3.14); s2.setData(10011776, 3.55); s1.showData(); s2.showData(); accessing or invoking member functions } Syntax: object_name . member_function_name member access operator 8/15
  • 9. A Simple Class: Sending a message to an object 1 . Through which objects interact with each other Student:s1 2. Whom - object name idnum action - method name gpa parameters setData showData() showData A C++ statement: s1.showData() 9/15
  • 10. A Simple Program: How it works? Student s1, s2; CLASS: OBJECTS: Student Student:s1 Student:s2 int idnum; int idnum; int idnum; double gpa; double gpa; double gpa; void setData(int, void setData(int, void setData(int, double); double); double); void showData(); void showData(); void showData(); 10/15
  • 11. A Simple Program: How it works? What is the output ? s1.setData(10016666, 3.14); s2.setData(10011776, 3.55); s1.showData(); s2.showData(); Student:s1 Student:s2 idnum 10016666 idnum 10011776 gpa 3.14 gpa 3.55 void setData(int, void setData(int, double); double); void showData(); void showData(); 11/15
  • 12. A simple program example #include <iostream.h> void main() { class Student Student aStudent; { private: aStudent.setIdNum(10019999); int idNum; char studName[20]; double gpa; aStudent.setName(‘Robbie’); public: aStudent.setGPA(3.57); void displayStudentData(); void setIdNum(int); aStudent.displayStudentData(); void setName(char[]); void setGPA(double); } }; //Implementation - refer to notes page 2 (Lecture 7). 12/15
  • 13. A simple program example #include <iostream.h> void main() class Distance { { private: Distance dist1, dist2; int feet; dist1.setDistance(11, 6.25); float inches; dist2.getDistance(); public: void setDistance(int ft, float in) //display lengths { feet = ft; inches = in; } cout << "ndist1 = "; void getDistancet() dist1.showDistance(); { cout << "nEnter feet: "; cin>>feet; cout << endl; cout << "Enter inches: "; cin>>inches; } cout << "ndist2 = "; void showDistance() dist2.showDistance(); { cout << feet << "'-" << inches << '"'; } cout << endl; }; } 13/15
  • 14. UML - Unified Modeling Language • UML are used for drawing models – Class diagram is one of the types of UML diagrams. – They Identify classes and their relationships • How to draw class diagram? Car Wheel Association model model color 1 n width speed drive ( ) change ( ) stop ( ) More than 1 turn( ) Multiplicity 14/15
  • 15. OOP Revisited 1. Major benefit - close correspondence between the real-world things being modeled – Everything about a real-world thing is included in its class description. ( characteristics & behaviour ) • This makes it easy to conceptualize a programming problem. You simply – figure out what parts of the problem can be most usefully represented as objects, and then – put all the data and functions connected with that object into the class. • For small programs, you can often proceed by trial and error. • For larger programs, you need to learn Object-Oriented Design (OOD) methodologies. 15/15
  • 16. Write a program to add two numbers ( Unstructured Programming) #include <iostream.h> void main( ) { int a,b,c; cin >> a >> b; c= a+b; cout<<c; c=a-b; cout<<c; } 16/15
  • 17. Write a program to add two numbers (structured Programming) #include <iostream.h> void main( ) int a,b,c; { input ( ){ cin>>a>>b;} input( ); add() add( ); { c= a+b; } print( ); sub( ); sub( ) print( ); {c= a-b;} } print() 17/15 {cout<<c;}
  • 18. OOP #include <iostream.h> class sample { Private : void main( ) int a,b,c; { Public: sample s; input ( ){ cin>>a>>b;} s.input( ); add() s.add( ); { c= a+b; } s.print( ); sub( ) {c= a-b;} s.sub( ); print() s.print( ); {cout<<c;} } }; 18/15
  • 19. Constructors and Destructors Learn about: i) Constructors ii) Destructors iii) When and how constructors & desctructors are called? 19
  • 20. What is a Constructor? • A member function that is executed automatically each time an object is created. • Must have exactly the same name as the class name. • No return type is used for constructors. • Purpose: Used to initialize the Data Members Example Next Slide 20/15
  • 21. Constructors: Definition #include <iostream.h> class Student // class declaration { private: int idNum; //class data double gpa; public: Student() { cout<<“An object of Student is created!!”<<endl; } void setData(int, double) ; void showData(); }; // Implementation of member functions 21/15
  • 22. Constructors: Definition #include <iostream.h> class Student // class declaration { : public: Student() { cout<<“An object of Student is created!!”<<endl; } : }; // Implementation of member functions void main() { Student s1, s2; Constructor is called twice!! : } What is the output? 22/15
  • 23. Types of Constructor? • Two types : default & multi argument constructor • A constructor without argument is called a default constructor. • A constructor can be overloaded. Ie ( there can be another constructor with same name ) • One of the most common tasks a constructor does is to initialize data members. For example, Student s1; Student:s1 Student() idNum gpa 0 { idNum = 0; 0.0 gpa = 0.0; } Student() setData(); showData(); Initialize to default values. 23/15
  • 24. Types of Constructor • A multi-argument constructor can initialize data members to values passes as arguments. For example, Student(int num, double result) Student s1(1001, 3.14); { idNum = num; Student:s1 gpa = result; } idNum 1001 gpa 3.14 Student() setData(); Initialize with arguments showData(); passed to it 24/15
  • 25. Default and overloaded Constructor: A simple program example #include <iostream.h> void main() class Student { { private: Student s1; int idNum; s1.setData(6666, 3.14); double gpa; public: Student s2(1776, 3.55); Student() : { cout<<“An object is created”<<endl; } } Student:s1 Student:s2 Student(int id, double result) idNum 6666 idNum 1776 { idnum = id; gpa = result; } gpa 3.14 gpa 3.55 void setData(); void showData(); }; Student() Student() //Implementation - refer to notes page 3 setData(); setData(); (Lecture 8). showData(); 25/15 showData();
  • 26. Constructor: Initializer list • Preferred way of initializing the data members using constructors is as follows: • Student(): idnum(0), gpa(0.0) { } Student(int id, double result): idnum(id), gpa(result) { } Counter() : count(0) { } SomeClass() : m1(7), m2(33), m3(4) { } Student( ) Student ( int id,double result) { idnum = 0; gpa =0.0;} { idnum = id; gpa = result;} 26/15
  • 27. Constructor: Other Example #include <iostream.h> void main() { Counter c1, c2; class Counter { private: cout << "nc1="<< c1.get_count(); int count; cout << "nc2=" << c2.get_count(); public: c1.inc_count(); //increment c1 Counter() : count(0) c2.inc_count(); //increment c2 { //empty body*} c2.inc_count(); //increment c2 void inc_count() { count++; } cout << "nc1=" << c1.get_count(); int get_count() { return count; } cout << "nc2=" << c2.get_count(); }; What is the output? // refer to page 4, Lecture 8 } 27/15
  • 28. What is a Destructor? • A member function that is called automatically each time an object is destroyed. • Has the same name as the constructor but is preceded by a tilde (~). • No return type and take no arguments. • Purpose : de-allocate the memory allotted for the data members • EG : class xyz { private : data members 28/15 public:
  • 29. Destructor: Definition #include <iostream.h> class Student // class declaration { private: int idNum; //class data double gpa; public: ~Student() { cout<<“An object has been destroyed!!”<<endl; } void setData(int, double) ; void showData(); }; // Implementation of member functions 29/15
  • 30. Constructors & Destructors: A Simple Example #include <iostream.h> void main() { Student s1, s2; class Student } { private: int idNum; public: Student() { cout<<“Object created.”<<endl;} Output: Object created. ~Student() Object created { cout<<“Object destroyed!”<<endl;} Object destroyed! }; Object destroyed! // refer to page 6, Lecture 8 30/15
  • 31. Constructors and Destructors: Global, Static and Local Objects • Constructors for global objects are called when the program begin execution. Destructors are called when program terminates. • Constructors for automatic local objects are called when execution reaches the point where the objects are defined. Destructors are called when objects leave their scope. • Constructors for statics objects are called only once when execution reaches the point where the objects are defined. Destructors are called when program terminates. 31/15
  • 32. Global, Static and Local Objects class Test { private: int data; public: Test (int value); ~Test(); ...}; Test :: Test (int value) { data = value; cout<<“ Object”<<data<<“ constructor”; } Test::~Test() { cout<<“Object”<,data<<“ destructor”<<endl; At this level, first object invokes Test first (1); its constructor ( global ) Cont… in the next slide 32/15
  • 33. Global, Static and Local Objects void main() { cout<<“ (global created before main)”<<endl; Test second(2); second object invokes cout<<“ (local automatic created in main)”<<endl; its constructor static Test third(3); third object invokes cout<<“ (local static created in main)”<<endl; its constructor func(); // function func is invoked link forth object invokes { Test forth(4); its constructor cout<<“ (local automatic crated in inner block in main)”<<endl; forth object invokes second, sixth, third, } its destructor and first object invokes } 33/15 its destructor respectively
  • 34. Global, Static and Local Objects void func() fifth object invokes { Test fifth(5); its constructor cout<<“ (local automatic created in func)”<<endl; static Test sixth(3); sixth object invoke cout<<“ (local static created in func)”<<endl; its constructor } fifth object invokes its destructor 34/15
  • 35. Global, Static and Local Objects Output: Object 1 constructor (global created before main) Object 2 constructor (local automatic created in main) Object 3 constructor (local static created in main) Object 5 constructor (local automatic created in func) Object 6 constructor (local static created in func) Object 5 destructor Object 4 constructor (local automatic created in inner block in main) Object 4 destructor Object 2 destructor Object 6 destructor Object 3 destructor Object 1 destructor Another example in the next slide 35/15
  • 36. Global, Static and Local Objects Test first (1) First object invokes void main() its constructor { cout<<“ (global created before main)”<<endl; Test second(2); second object invokes cout<<“ (local automatic created in main)”<<endl; its constructor static Test third(3); third object invokes cout<<“ (local static created in main)”<<endl; its constructor func(); // function func is invoked, refer to slide 16 forth object invokes { Test forth(4); its constructor cout<<“ (local automatic crated in inner block in main)”<<endl; } func(); //function func is invoked again 36/15 }
  • 37. Global, Static and Local Objects void func() fifth object invokes { Test fifth(5); its constructor cout<<“ (local automatic created in func)”<<endl; static Test sixth(3); sixth object DOESN’T invok cout<<“ (local static created in func)”<<endl; its constructor again } fifth object invokes its destructor 37/15
  • 38. Global, Static and Local Objects Output: Object 1 constructor (global created before main) Object 2 constructor (local automatic created in main) Object 3 constructor (local static created in main) Object 5 constructor (local automatic created in func) Object 6 constructor (local static created in func) Object 5 destructor Object 4 constructor (local automatic created in inner block in main) Object 4 destructor Object 5 constructor (local automatic created in func) (local static created in func) Object 5 destructor Object 2 destructor Object 6 destructor Object 3 destructor Object 1 destructor 38/15