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

Weitere ähnliche Inhalte

Was ist angesagt? (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
 

Andere mochten auch (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
 

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

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

Mehr von elearning_portal (6)

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

Kürzlich hochgeladen

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Kürzlich hochgeladen (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

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