SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
Data Structures using OOP C++                                         Lecture 1



References:
   1. E Balagurusamy ,”Object Oriented Programming with C++”, 4th edition,
      McGraw-Hill 2008.
   2. Robert L. Kruse and Alexander J. Ryba, “Data Structures and Program
      Design in C++”, Prentice-Hall 2000.


Introduction
There are two weaknesses related with structured programming. Firstly,
functions have unrestricted access to global data. This causes a program’s
structure difficult to conceptualize. In addition, it makes the program
difficult to modify. Any change made in a global data item may
necessitate rewriting all the functions that access that item. Secondly, the
arrangement of separate data and functions does a poor job of modeling
things in the real world. In the real world we deal with objects such as
people and cars. Such objects aren’t like data and they aren’t like
functions. Complex real-world objects have both data and functions.
Therefore there was a need for a new programming approach which is
called Object-Oriented Programming.

Object-Oriented Programming (OOP)
   • OOP incorporates the best features of structured programming with
       several powerful new concepts.
   •   It provides a new way of thinking, organizing and developing
       programs.
   • OOP allows decomposition of a problem into a number of entities
       called objects and then builds data and functions around these
       objects.
   • OOP treats data as a critical element in the program development
       and does not allow it to flow freely around the system. The data of

Ass. Lec. Zainab Mahmood Fadhil                                         Page 1
Data Structures using OOP C++                                       Lecture 1




      an object can be accessed only by the functions associated with that
      object. However, functions of one object can access the functions
      of other objects.


Fundamental OOP Concepts
The principles of OOP include:
   • Class: is like a blueprint (general form) used to create objects. A
      class also is an abstract data type that can be treated like any other
      built-in data type. A class defines the attributes of its objects and
      the methods that can be applied to its objects.
   • Object: is the basic run-time entity in an object-oriented system. It
      may represent a person, a place, a bank account, etc. An object is
      also called an instance of a class.
   • Encapsulation: is the mechanism that binds together data and
      functions into a single unit (called class). The data is not accessible
      to the outside world, and only the functions which are wrapped in
      the class can access it. This insulation of data from direct access is
      called data hiding or information hiding.
   • Inheritance: is the process by which objects of one class acquire
      the properties of objects of another class. It supports the concept of
      hierarchical classification. It also provides the idea of reusability.
      This means that we can add additional features to an existing class
      without modifying it.
   • Polymorphism: is the ability for objects of different classes related
      by inheritance to respond differently to the same message. The
      same message sent to many different types of objects takes on
      “many forms”--hence the term polymorphism.
Ass. Lec. Zainab Mahmood Fadhil                                        Page 2
Data Structures using OOP C++                                     Lecture 1




Classes
The general form of a class declaration in C++ is:
      class class_name
      {
           private:
                variable           declarations;
                function           declarations;
           public:
                variable           declarations;
                function           declarations;
      };

- The keyword class indicates that an abstract data type called
   class_name will be specified.
- The class body is enclosed within braces and terminated by a
   semicolon.
- The variables declared inside the class are known as data members
   and the functions are known as member functions.
- These functions and variables are usually grouped under two sections:
   namely, private and public.
- Only the member functions can have access to the private data
   members and private functions. However, the public members can be
   accessed from outside the class.
- Note that declaring data variables as public defeat the idea of data
   hiding and therefore should be avoided.




Ass. Lec. Zainab Mahmood Fadhil                                      Page 3
Data Structures using OOP C++                                        Lecture 1




A Simple Class Example
      class item
      {
           private:
                int number;
                float cost;
           public:
                void getdata(int               a, float     b);
                void putdata();
      };

Here, we have defined a class called item. This name is used to declare
objects of that class. The data members (number and cost) are declared
as private, while the member functions (getdata() and putdata())
are declared as public. As mentioned earlier, these two functions provide
the only access to the two data members from outside the class. Note that,
at this stage class definition does not allocate any memory space.


Objects
Once a class has been defined, we can create objects of that type as
follows:
                    item        x;
This statement creates an object x of type item. At this stage, memory
space is allocated to the object x. We may also declare more than one
object in one statement, for example
                   item         x, y, z;
Another way to create objects is by placing their names immediately after
the closing brace in the class definition, for example:




Ass. Lec. Zainab Mahmood Fadhil                                        Page 4
Data Structures using OOP C++                                     Lecture 1



      class       item
      {
      ………
      ………
      } x, y, z;


Accessing Class Members
As previously mentioned, the public member functions can be accessed
only from outside the class. This can be done using the dot operator, for
example
             x.getdata(100, 75.5);
This function call statement is valid and assigns the value 100 to number
and 75.5 to cost of the object x by implementing the getdata()
function.
Similarly, the statement
             x.putdata();
would display the values of number and cost.
While the statement
             x.number =100;
is illegal because number is a private member and cannot be accessed
from outside the class.
When a variable is declared as public, it can be accessed by the objects
directly, for example:




Ass. Lec. Zainab Mahmood Fadhil                                      Page 5
Data Structures using OOP C++                                     Lecture 1



      class    xyz
      {
           private:
                int         x;
                int         y;
           public:
                int         z;
      };
      …………
      …………
      xyz   p;                  // create object p
      p.x = 0;                  // error, x is private
      p.z = 10;                 // OK, z is public
      …………
      …………
However, the public declaration of data conflicts with the OOP concept
data hiding and therefore should be avoided.


Definition of Member Functions
Class member functions can be defined in two places:
Outside the Class Definition
Example:
      void      item :: getdata(int a, float b)
      {
             number = a;
             cost = b;
      }

Here, the membership label item :: tells the compiler that the function
getdata() belongs to the class item. That is, the scope of the function
getdata() is restricted to the class item specified in the header line.
The symbol :: is called the scope resolution operator. Note the
statements
             number = a;              cost =     b;



Ass. Lec. Zainab Mahmood Fadhil                                     Page 6
Data Structures using OOP C++                                       Lecture 1




show that the member functions can have direct access to private data
items. Similarly, the function putdata() is defined outside the class
item as follows:
      void      item :: putdata()
      {
              cout << ”Number :” << number << “n” ;
              cout << ”Cost       :” << cost << “n” ;
      }

Inside the Class Definition
Example:
    class item
    {
      private:
          int   number;
          float   cost;
      public:
           void   getdata(int a, float b);
           void putdata()
           {
             cout << ”Number :” << number << “n” ;
             cout << ”Cost       :” << cost << “n” ;
           }
    };

Note: Normally, only small functions are defined inside the class
definition.


A Complete C++ Program with Class
The following program includes all the details discussed so far:
#include <iostream>
using namespace std;
class item
     {
     private:
          int   number;
          float cost;

Ass. Lec. Zainab Mahmood Fadhil                                       Page 7
Data Structures using OOP C++                    Lecture 1




       public:
            void   getdata(int a, float b);
            void putdata()
            {
               cout << “number :” << number << “n”;
               cout << “cost   :” << cost   << “n”;
            }
       };

void      item :: getdata(int a, float     b)
{
        number = a;
        cost = b;
}

void      main()
{
       item   x;         //create object    x
       cout << “nObject    x “ << “n;
       x.getdata(100, 299.95);
       x.putdata();

       item   y;     //create another object y
       cout << “nObject   y “ << “n;
       x.getdata(200, 175. 50);
       x.putdata();
}


The output of the above program is:
Object x
number :100
cost    :299.95
Object y
number :200
cost   :175.5




Ass. Lec. Zainab Mahmood Fadhil                    Page 8
Data Structures using OOP C++                                    Lecture 1




Nesting of Member Functions
We have shown that a class member function can be called only by an
object of that class using a dot operator. However, a member function can
be called inside another member function of the same class. This is called
nesting of member functions.
Example:
#include <iostream>
using namespace std;
class set
{
     private:
          int   m, n;
     public:
          void input();
          void display();
          int largest();
};

int    set :: largest()
{
      if(m >= n)
           return m;
      else
           return n;
}

void set :: input()
{
     cout << “Input values of m and n” << “n”;
     cin >> m >> n;
}

void set :: display()
{
  cout << “Largest value = ”
       << largest() << “n”;             //calling member function
}

void main()
{
Ass. Lec. Zainab Mahmood Fadhil                                     Page 9
Data Structures using OOP C++                                     Lecture 1



       set A;
       A.input();
       A.display();
}

The output of the above program would be:
Input values of m and n
25 18
Largest value = 25


Private Member Functions
Some tasks such as deleting a customer account, or providing an
increment to an employee may require certain functions to be hidden (like
private data) from the outside calls. We can place these functions in the
private section. Note that a private member function can only be called by
another member function of its class, and cannot be called by an object.
Example:
class sample
{
     private:
          int        m;
          void       read();       // private member function
     public:
          void         update();
          void         write();
};
…………
…………
sample   s1;
s1.read();           // won’t work; objects cannot access
                     // private members from outside the class
…………
…………

The function call statement
        s1.read();

Ass. Lec. Zainab Mahmood Fadhil                                     Page 10
Data Structures using OOP C++                                          Lecture 1




is illegal. Instead, the function read() can be called by the function
update() to update the value of m.
void     sample :: update()
{
       read();        // simple call; no object used
}


Constructors
A constructor is a member function whose name is the same as the class
name. The constructor is used to initialize the objects of its class, i.e. it
constructs the values of data members of the class. The constructor is
automatically invoked whenever object of its associated class is created.
Example:
       #include <iostream>
       using namespace std;
       class integer
       {
          private:
              int m, n;
          public:
              integer();    // constructor declaration
              void printdata();
       };
       integer :: integer()    // constructor definition
       {
            m = 0;   n = 0;
       }
       void integer :: printdata()
       {
            cout << “ m = “ << m << “n”
                 << “n = “ << n << “n”;
       }
       void   main()
       {



Ass. Lec. Zainab Mahmood Fadhil                                         Page 11
Data Structures using OOP C++                                      Lecture 1



              integer intl;
              intl.printdata();
        }

The declaration statement
              integer      intl;
not only creates the object intl of type integer but also
automatically initializes its data members m and n to zero.
The output of the above program is
m=0
n=0

Notes
   • The constructor should be declared in the public section.
   • The constructor does not have return type, (not even void), and
        therefore it cannot return any value.
   • There is no need to write any statement to invoke the constructor
        function because it is invoked automatically when the object is
        created.
   • A constructor that accepts no arguments is called the default
        constructor.
   • If no constructor is defined, then the compiler creates an implicit
        constructor.
   • The constructor can take arguments like other C++ functions. This
        is called parameterized constructor.


Parameterized Constructors
Sometimes we need to initialize the data elements of different objects
with different values when they are created. This can be done by passing
Ass. Lec. Zainab Mahmood Fadhil                                      Page 12
Data Structures using OOP C++                                       Lecture 1




arguments to the constructor function when objects are created. Such
constructor is called parameterized constructor.
Example:
#include <iostream>
using namespace std;
class     integer
{
  private:
    int    m, n;
  public:
    integer(int , int ); //parameterized constructor
    void printdata();
};
integer :: integer(int x, int y)
{     m = x;     n = y; }
void integer :: printdata()
{
cout << ”m = ” << m << “n”
      <<”n = ” << n << “n“;
}
void main()
{
integer intl(1, 100);
intl.printdata();
}

The output of the above program is
m=1
n = 100

Note that when we use parameterized constructor, we must pass the initial
values as arguments to the constructor function when an object is
declared. For example, in the above program, the following declaration
statement
      integer       intl;
may not work. In this case we need to define multiple constructors as in
the following example:

Ass. Lec. Zainab Mahmood Fadhil                                      Page 13
Data Structures using OOP C++                                   Lecture 1



#include <iostream>
using namespace std;
class     integer
{
  private:
    int    m, n;
  public:
    integer();
    integer(int , int ); //parameterized constructor
    void printdata();
};
integer :: integer() { m = 0;       n = 0; }
integer :: integer(int x, int y)
{     m = x;     n = y; }
void integer :: printdata()
{
cout << ”m = ” << m << “n”
      <<”n = ” << n << “n“;
}
void main()
{
integer intl1, intl2(1, 100);

cout<<”OBJECT 1 n”;
intl1.printdata();

cout<<”OBJECT 2 n”;
intl2.printdata();
}

The output of the above program is
OBJECT 1
m=0
n=0
OBJECT 2
m=1
n = 100

Note: When more than one constructor function is defined in a class, we
say that constructor overloading.


Ass. Lec. Zainab Mahmood Fadhil                                  Page 14
Data Structures using OOP C++                                       Lecture 1




Destructors
A destructor is a member function whose name is the same as the class
name but is preceded by a tilde ~ . The destructor is used to destroy the
objects that have been created by a constructor. For example, the
destructor for the class integer is defined as follows:
             ~integer() { }

Notes
• A destructor never takes any arguments nor does it return any value.
• A destructor will be invoked implicitly by the compiler upon exit
    from the program (or block or function) to free memory space.

Example:
#include <iostream>
using namespace std;
int count = 0;
class     alpha
{
public :
   alpha ()
    {
      count++;
      cout << “nObject#“ << count << “ is created ”;
    }
  ~alpha()
    {
      cout << “nObject#” << count << “ is destroyed ”;
      count--;
    }
};

void main()
{
     cout << “nnENTER MAINn”;

        alpha A1, A2, A3, A4;

Ass. Lec. Zainab Mahmood Fadhil                                      Page 15
Data Structures using OOP C++                                      Lecture 1



      {
      cout << “nnENTER BLOCKn”;
      alpha A5;
      alpha A6;
      }

      cout << “nnRE-ENTER MAIN THEN EXIT PROGRAM”;
}

The output of the above program is:
ENTER MAIN

Object#1 is created
Object#2 is created
Object#3 is created
Object#4 is created

ENTER BLOCK

Object#5 is created
Object#6 is created
Object#6 is destroyed
Object#5 is destroyed


RE-ENTER MAIN THEN EXIT PROGRAM
Object#4 is destroyed
Object#3 is destroyed
Object#2 is destroyed
Object#1 is destroyed


Note that the objects are destroyed in the reverse order of creation.




Ass. Lec. Zainab Mahmood Fadhil                                         Page 16

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
class and objects
class and objectsclass and objects
class and objects
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
C++ classes
C++ classesC++ classes
C++ classes
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Object and class
Object and classObject and class
Object and class
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
C++ classes
C++ classesC++ classes
C++ classes
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 aug
 
Basic c#
Basic c#Basic c#
Basic c#
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 

Destacado

[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 

Destacado (6)

[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 

Similar a C++ largest no between three nos

Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Object oriented programming C++
Object oriented programming C++Object oriented programming C++
Object oriented programming C++AkshtaSuryawanshi
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Boro
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Languagedheva B
 
Inheritance concepts Presentation (8).pptx
Inheritance concepts Presentation (8).pptxInheritance concepts Presentation (8).pptx
Inheritance concepts Presentation (8).pptxABHINAVARYANCSEA301
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfstudy material
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
concepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxconcepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxurvashipundir04
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3Atif Khan
 

Similar a C++ largest no between three nos (20)

Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Object oriented programming C++
Object oriented programming C++Object oriented programming C++
Object oriented programming C++
 
My c++
My c++My c++
My c++
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
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
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Language
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
 
Inheritance concepts Presentation (8).pptx
Inheritance concepts Presentation (8).pptxInheritance concepts Presentation (8).pptx
Inheritance concepts Presentation (8).pptx
 
chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
concepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptxconcepts of object and classes in OOPS.pptx
concepts of object and classes in OOPS.pptx
 
Class and object
Class and objectClass and object
Class and object
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 

Último

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Último (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

C++ largest no between three nos

  • 1. Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy ,”Object Oriented Programming with C++”, 4th edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, “Data Structures and Program Design in C++”, Prentice-Hall 2000. Introduction There are two weaknesses related with structured programming. Firstly, functions have unrestricted access to global data. This causes a program’s structure difficult to conceptualize. In addition, it makes the program difficult to modify. Any change made in a global data item may necessitate rewriting all the functions that access that item. Secondly, the arrangement of separate data and functions does a poor job of modeling things in the real world. In the real world we deal with objects such as people and cars. Such objects aren’t like data and they aren’t like functions. Complex real-world objects have both data and functions. Therefore there was a need for a new programming approach which is called Object-Oriented Programming. Object-Oriented Programming (OOP) • OOP incorporates the best features of structured programming with several powerful new concepts. • It provides a new way of thinking, organizing and developing programs. • OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. • OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. The data of Ass. Lec. Zainab Mahmood Fadhil Page 1
  • 2. Data Structures using OOP C++ Lecture 1 an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects. Fundamental OOP Concepts The principles of OOP include: • Class: is like a blueprint (general form) used to create objects. A class also is an abstract data type that can be treated like any other built-in data type. A class defines the attributes of its objects and the methods that can be applied to its objects. • Object: is the basic run-time entity in an object-oriented system. It may represent a person, a place, a bank account, etc. An object is also called an instance of a class. • Encapsulation: is the mechanism that binds together data and functions into a single unit (called class). The data is not accessible to the outside world, and only the functions which are wrapped in the class can access it. This insulation of data from direct access is called data hiding or information hiding. • Inheritance: is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. It also provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. • Polymorphism: is the ability for objects of different classes related by inheritance to respond differently to the same message. The same message sent to many different types of objects takes on “many forms”--hence the term polymorphism. Ass. Lec. Zainab Mahmood Fadhil Page 2
  • 3. Data Structures using OOP C++ Lecture 1 Classes The general form of a class declaration in C++ is: class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; }; - The keyword class indicates that an abstract data type called class_name will be specified. - The class body is enclosed within braces and terminated by a semicolon. - The variables declared inside the class are known as data members and the functions are known as member functions. - These functions and variables are usually grouped under two sections: namely, private and public. - Only the member functions can have access to the private data members and private functions. However, the public members can be accessed from outside the class. - Note that declaring data variables as public defeat the idea of data hiding and therefore should be avoided. Ass. Lec. Zainab Mahmood Fadhil Page 3
  • 4. Data Structures using OOP C++ Lecture 1 A Simple Class Example class item { private: int number; float cost; public: void getdata(int a, float b); void putdata(); }; Here, we have defined a class called item. This name is used to declare objects of that class. The data members (number and cost) are declared as private, while the member functions (getdata() and putdata()) are declared as public. As mentioned earlier, these two functions provide the only access to the two data members from outside the class. Note that, at this stage class definition does not allocate any memory space. Objects Once a class has been defined, we can create objects of that type as follows: item x; This statement creates an object x of type item. At this stage, memory space is allocated to the object x. We may also declare more than one object in one statement, for example item x, y, z; Another way to create objects is by placing their names immediately after the closing brace in the class definition, for example: Ass. Lec. Zainab Mahmood Fadhil Page 4
  • 5. Data Structures using OOP C++ Lecture 1 class item { ……… ……… } x, y, z; Accessing Class Members As previously mentioned, the public member functions can be accessed only from outside the class. This can be done using the dot operator, for example x.getdata(100, 75.5); This function call statement is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing the getdata() function. Similarly, the statement x.putdata(); would display the values of number and cost. While the statement x.number =100; is illegal because number is a private member and cannot be accessed from outside the class. When a variable is declared as public, it can be accessed by the objects directly, for example: Ass. Lec. Zainab Mahmood Fadhil Page 5
  • 6. Data Structures using OOP C++ Lecture 1 class xyz { private: int x; int y; public: int z; }; ………… ………… xyz p; // create object p p.x = 0; // error, x is private p.z = 10; // OK, z is public ………… ………… However, the public declaration of data conflicts with the OOP concept data hiding and therefore should be avoided. Definition of Member Functions Class member functions can be defined in two places: Outside the Class Definition Example: void item :: getdata(int a, float b) { number = a; cost = b; } Here, the membership label item :: tells the compiler that the function getdata() belongs to the class item. That is, the scope of the function getdata() is restricted to the class item specified in the header line. The symbol :: is called the scope resolution operator. Note the statements number = a; cost = b; Ass. Lec. Zainab Mahmood Fadhil Page 6
  • 7. Data Structures using OOP C++ Lecture 1 show that the member functions can have direct access to private data items. Similarly, the function putdata() is defined outside the class item as follows: void item :: putdata() { cout << ”Number :” << number << “n” ; cout << ”Cost :” << cost << “n” ; } Inside the Class Definition Example: class item { private: int number; float cost; public: void getdata(int a, float b); void putdata() { cout << ”Number :” << number << “n” ; cout << ”Cost :” << cost << “n” ; } }; Note: Normally, only small functions are defined inside the class definition. A Complete C++ Program with Class The following program includes all the details discussed so far: #include <iostream> using namespace std; class item { private: int number; float cost; Ass. Lec. Zainab Mahmood Fadhil Page 7
  • 8. Data Structures using OOP C++ Lecture 1 public: void getdata(int a, float b); void putdata() { cout << “number :” << number << “n”; cout << “cost :” << cost << “n”; } }; void item :: getdata(int a, float b) { number = a; cost = b; } void main() { item x; //create object x cout << “nObject x “ << “n; x.getdata(100, 299.95); x.putdata(); item y; //create another object y cout << “nObject y “ << “n; x.getdata(200, 175. 50); x.putdata(); } The output of the above program is: Object x number :100 cost :299.95 Object y number :200 cost :175.5 Ass. Lec. Zainab Mahmood Fadhil Page 8
  • 9. Data Structures using OOP C++ Lecture 1 Nesting of Member Functions We have shown that a class member function can be called only by an object of that class using a dot operator. However, a member function can be called inside another member function of the same class. This is called nesting of member functions. Example: #include <iostream> using namespace std; class set { private: int m, n; public: void input(); void display(); int largest(); }; int set :: largest() { if(m >= n) return m; else return n; } void set :: input() { cout << “Input values of m and n” << “n”; cin >> m >> n; } void set :: display() { cout << “Largest value = ” << largest() << “n”; //calling member function } void main() { Ass. Lec. Zainab Mahmood Fadhil Page 9
  • 10. Data Structures using OOP C++ Lecture 1 set A; A.input(); A.display(); } The output of the above program would be: Input values of m and n 25 18 Largest value = 25 Private Member Functions Some tasks such as deleting a customer account, or providing an increment to an employee may require certain functions to be hidden (like private data) from the outside calls. We can place these functions in the private section. Note that a private member function can only be called by another member function of its class, and cannot be called by an object. Example: class sample { private: int m; void read(); // private member function public: void update(); void write(); }; ………… ………… sample s1; s1.read(); // won’t work; objects cannot access // private members from outside the class ………… ………… The function call statement s1.read(); Ass. Lec. Zainab Mahmood Fadhil Page 10
  • 11. Data Structures using OOP C++ Lecture 1 is illegal. Instead, the function read() can be called by the function update() to update the value of m. void sample :: update() { read(); // simple call; no object used } Constructors A constructor is a member function whose name is the same as the class name. The constructor is used to initialize the objects of its class, i.e. it constructs the values of data members of the class. The constructor is automatically invoked whenever object of its associated class is created. Example: #include <iostream> using namespace std; class integer { private: int m, n; public: integer(); // constructor declaration void printdata(); }; integer :: integer() // constructor definition { m = 0; n = 0; } void integer :: printdata() { cout << “ m = “ << m << “n” << “n = “ << n << “n”; } void main() { Ass. Lec. Zainab Mahmood Fadhil Page 11
  • 12. Data Structures using OOP C++ Lecture 1 integer intl; intl.printdata(); } The declaration statement integer intl; not only creates the object intl of type integer but also automatically initializes its data members m and n to zero. The output of the above program is m=0 n=0 Notes • The constructor should be declared in the public section. • The constructor does not have return type, (not even void), and therefore it cannot return any value. • There is no need to write any statement to invoke the constructor function because it is invoked automatically when the object is created. • A constructor that accepts no arguments is called the default constructor. • If no constructor is defined, then the compiler creates an implicit constructor. • The constructor can take arguments like other C++ functions. This is called parameterized constructor. Parameterized Constructors Sometimes we need to initialize the data elements of different objects with different values when they are created. This can be done by passing Ass. Lec. Zainab Mahmood Fadhil Page 12
  • 13. Data Structures using OOP C++ Lecture 1 arguments to the constructor function when objects are created. Such constructor is called parameterized constructor. Example: #include <iostream> using namespace std; class integer { private: int m, n; public: integer(int , int ); //parameterized constructor void printdata(); }; integer :: integer(int x, int y) { m = x; n = y; } void integer :: printdata() { cout << ”m = ” << m << “n” <<”n = ” << n << “n“; } void main() { integer intl(1, 100); intl.printdata(); } The output of the above program is m=1 n = 100 Note that when we use parameterized constructor, we must pass the initial values as arguments to the constructor function when an object is declared. For example, in the above program, the following declaration statement integer intl; may not work. In this case we need to define multiple constructors as in the following example: Ass. Lec. Zainab Mahmood Fadhil Page 13
  • 14. Data Structures using OOP C++ Lecture 1 #include <iostream> using namespace std; class integer { private: int m, n; public: integer(); integer(int , int ); //parameterized constructor void printdata(); }; integer :: integer() { m = 0; n = 0; } integer :: integer(int x, int y) { m = x; n = y; } void integer :: printdata() { cout << ”m = ” << m << “n” <<”n = ” << n << “n“; } void main() { integer intl1, intl2(1, 100); cout<<”OBJECT 1 n”; intl1.printdata(); cout<<”OBJECT 2 n”; intl2.printdata(); } The output of the above program is OBJECT 1 m=0 n=0 OBJECT 2 m=1 n = 100 Note: When more than one constructor function is defined in a class, we say that constructor overloading. Ass. Lec. Zainab Mahmood Fadhil Page 14
  • 15. Data Structures using OOP C++ Lecture 1 Destructors A destructor is a member function whose name is the same as the class name but is preceded by a tilde ~ . The destructor is used to destroy the objects that have been created by a constructor. For example, the destructor for the class integer is defined as follows: ~integer() { } Notes • A destructor never takes any arguments nor does it return any value. • A destructor will be invoked implicitly by the compiler upon exit from the program (or block or function) to free memory space. Example: #include <iostream> using namespace std; int count = 0; class alpha { public : alpha () { count++; cout << “nObject#“ << count << “ is created ”; } ~alpha() { cout << “nObject#” << count << “ is destroyed ”; count--; } }; void main() { cout << “nnENTER MAINn”; alpha A1, A2, A3, A4; Ass. Lec. Zainab Mahmood Fadhil Page 15
  • 16. Data Structures using OOP C++ Lecture 1 { cout << “nnENTER BLOCKn”; alpha A5; alpha A6; } cout << “nnRE-ENTER MAIN THEN EXIT PROGRAM”; } The output of the above program is: ENTER MAIN Object#1 is created Object#2 is created Object#3 is created Object#4 is created ENTER BLOCK Object#5 is created Object#6 is created Object#6 is destroyed Object#5 is destroyed RE-ENTER MAIN THEN EXIT PROGRAM Object#4 is destroyed Object#3 is destroyed Object#2 is destroyed Object#1 is destroyed Note that the objects are destroyed in the reverse order of creation. Ass. Lec. Zainab Mahmood Fadhil Page 16