Object Oriented Programming -Classes and Objects | GlobalEducore

Object-Oriented Programming

PROGRAMMING TECHNIQUES

•   Unstructured programming

•   Procedural programming

•   Modular programming

•   Object-oriented programming

•   Generic programming         

    UNSTRUCTURED PROGRAMMING

•   Only one Program i.e. main Program

•   All the sequences of commands or statements in one programs called the main Program

•   E.g. Fortran, assembly language, old Basic

   MODULAR PROGRAMMING

•   Procedures with some common functionality are grouped together into separate modules
•   Program is categorized into several smaller modules
•   Each module can have its own data

   Procedural Oriented Language

• Conventional programming, using a high-level language such as COBOL, FORTRAN, and C are commonly-known as Procedure oriented language (POP).
• In POP numbers of functions are written to accomplish the tasks




Object Oriented Programming | Classes and Objects

    Procedure Oriented Language

         - Characteristics -
• Emphasis is on doing things (algorithms).
• Larger programs are divided into smaller
  programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from
  function to function.
• Employs top-down approach in program design.
    Procedural Oriented Language
           - Limitations -
• Data move freely around the program and are
  therefore vulnerable to changes caused by any
  function in the program.
• It does not model very well the real world
  problems.
   Object Oriented Programming
• OOP treats data as critical element
• Ties data more closely to the functions that
  operate on it & allows decomposition of
  problem into objects.
                             OBJECT

                              Operations

                                   Data

       OBJECT                                        OBJECT

       Operations                                    Operations

         Data                 Communication            Data

                    Santosh A. Darade, SITS, Narhe
                      Procedure Oriented Programming                        Object Oriented Programming
                       In POP, program is divided into small parts           In OOP, program is divided into parts
  Divided Into
                                    called functions                                    called objects

                     In POP, Importance is not given to data but to     In OOP, Importance is given to the data rather
  Importance         functions as well as sequence of actions to be   than procedures or functions because it works as a
                                          done                                            real world

   Approach                 POP follows Top Down approach                      OOP follows Bottom Up approach

                                                                       OOP has access specifiers named Public, Private,
Access Specifiers       POP does not have any access specifier.
                                                                                       Protected, etc.

                     In POP, Data can move freely from function to     In OOP, objects can move and communicate with
 Data Moving
                                function in the system                      each other through member functions

                     To add new data and function in POP is not so      OOP provides an easy way to add new data and
   Expansion
                                        easy                                              function

                       In POP, Most function uses Global data for       In OOP, data can not move easily from function
  Data Access       sharing that can be accessed freely from function to function, it can be kept public or private so we
                                to function in the system                       can control the access of data

                      POP does not have any proper way for hiding         OOP provides Data Hiding so provides more
  Data Hiding
                                data so it is less secure                                 security

   Examples           Example of POP are : C, VB, FORTRAN, Pascal      Example of OOP are : C++, JAVA, VB.NET, C#.NET
        Fundamentals of OOP
•   Objects
•   Classes
•   Encapsulation
•   Data Abstraction
•   Inheritance
•   Polymorphism
•   Dynamic Binding
•   Message Passing
                  Objects
• OOP uses objects as its fundamental building
  blocks.
• Objects are the basic run-time entities in an
  object-oriented system.
• Every object is associated with data and
  functions which define meaningful operations
  on that object.
• Object is a real world existing entity.
• Object is an Instance of a particular class.
            Object

            Operation




Operation   Attributes   Operation




             Operation
  Example: StudentObject

                 Enroll()


                st_name
                 st_id      Displayinfo()
Performance()
                 branch
                semester


                Result()
                      Class
• Class is a collection of similar objects.




                        Class
              Encapsulation
• It is a mechanism that associates the code and
  the data & it manipulates into a single unit
  and keeps them safe from external
  interference and misuse.
         Encapsulation

Class: student

Attributes: st_name, st_id,
            branch, semester
Functions: Enroll()
           Displayinfo()
           Result()
           Performance()
            Data Abstraction
• A data abstraction is a simplified view of an
  object that includes only features one is
  interested in while hides away the
  unnecessary details.
                Inheritance
• Inheritance is the mechanism to provides the
  power of reusability and extendibility.
• Inheritance is the process by which one object
  can acquire the properties of another
  object.
              Inheritance

                            Parent class
                                Or
                             Base class
                Point

Child class
    Or
 Derived
  class          Line
              Polymorphism
• Polymorphism means that the same thing can
  exist in two forms.

• Polymorphism is in short the ability to call
  different functions by just using one type of
  function call.
      Polymorphism
5+9                  Str + ing


         +
                             22
            Dynamic Binding
• Dynamic Binding is the process of linking of
  the code associated with a procedure call at
  the run-time
           Message Passing
• The process of invoking an operation on an
  object.
• In response to a message the corresponding
  method is executed in the object
          Message Passing
StudentObject                    FacultyObject


                   Performance




                MgmtObject       Performance
 Result
                    USE OF C++

•   C++ is used by hundreds of thousands of
    programmers in essentially every application domain.
•   C++ is being highly used to write device drivers and
    other softwares that rely on direct manipulation of
    hardware under real-time constraints.
•   C++ is widely used for teaching and research because
    it is clean enough for successful teaching of basic
    concepts.
•   Anyone who has used either an Apple Macintosh or a
    PC running Windows has indirectly used C++ because
    the primary user interfaces of these systems are26
    written in C++.
      C++ PROGRAM STRUCTURE
#include <iostream>// headers
using namespace std; // use std namespace
// main() is where program execution begins.
 int main()
{
        cout << "Hello World"; // prints Hello World//
                                    // statements
        return 0;
}




                                                         27
                    C++ IDENTIFIER
•   A C++ identifier is a name used to identify a variable, function,
    class, module, or any other user-defined item.
•   Starts with a letter A to Z or a to z or an underscore (_)
    followed by zero or more letters, underscores, and digits (0 to
    9).
•   C++ does not allow punctuation characters such as @, $, and %
    within identifiers
•   C++ is a case-sensitive programming language
•   E.g. Mohd, zara, abc, move_name, a_123
          myname50, _temp, j, a23b9, retVal
                                                                  28
29
                     COMMENTS
•   Program comments are explanatory statements that you can
    include in the C++ code that you write and helps anyone reading
    it's source code
•   All programming languages allow for some form of comments.
•   C++ supports single-line and multi-line comments
•   C++ comments start with /* and end with */.
•   /* This is a comment */
•      /*
      C++ comments can also
       * span multiple lines
       */
•   // prints Hello World ---single line comment                30
31
32
                DATA TYPE PROGRAM
•   #include <iostream>
•   using namespace std;
•   int main(){
    cout << "Size of char : " << sizeof(char) << endl;
    cout << "Size of int : " << sizeof(int) << endl;
    cout << "Size of short int : " << sizeof(short int) << endl;
    cout << "Size of long int : " << sizeof(long int) << endl;
    cout << "Size of float : " << sizeof(float) << endl;
    cout << "Size of double : " << sizeof(double) << endl;
    cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;

    return 0;
}                                                                  33
// endl, which inserts a new-line character after every line
          Variable Declaration
• A variable defines a location in the memory that
  holds a value which can be modified later.
• Syntax:
      type variable_list;
• In the above syntax "type" refers to any one of the
  C++ data types.
              Declaring Variables
• Variables in C++ should be declared before they are used in
  the code block.
       #include <iostream.h>
       void main()
       {
        int n = 10;
       cout << "Integer value is:"<< n << '\n';
       }

• Result:
      Integer value is: 10
      In the above example "n" is an integer variable declared
      using return type "int".
Rules for Naming variables in C++
• Always the first character of a variable must be a
  letter or an underscore.
• The variable name cannot start with a digit.
• Other characters should be either letters, digits,
  underscores.
• There is no limit for the length of variables.
• Declared keywords cannot be used as a variable
  name.
• Upper and lower case letters are distinct.
               Variable Scope
• A scope is a region of the program and broadly
  speaking there are three places, where
  variables can be declared:
  – Inside a function or a block which is called local
    variables,
  – In the definition of function parameters which is
    called formal parameters
  – Outside of all functions which is called global
    variables.
             Local variables
• Parameters and variables declared inside the
  definition of a function are local.
• They only exist inside the function body.
• Once the function returns, the variables no
  longer exist!
   Example Using Local Variables:
#include <iostream.h>
int main ()
      {              // Local variable declaration:
             int a, b;
             int c;
                     // actual initialization
             a = 10;
             b = 20;
             c = a + b;
             cout << c;
             return 0;
      }
            Global Variables
• We can declare variables outside of any
  function definition – these variables are
  global variables.
• Any function can access/change global
  variables.
• Example: flag that indicates whether
  debugging information should be printed.
     Example Using Global and Local
               Variables
#include <iostream>
                // Global variable declaration:
   int g;
int main ()
   {            // Local variable declaration:
        int a, b;
                // actual initialization
        a = 10;
        b = 20;
        g = a + b;
        cout << g;
        return 0;
  }
             Constants (const)
• Constants refer to fixed values that the
  program may not alter
• Defining Constants:
     • Using #define preprocessor.
     • Using const keyword.
       The #define Preprocessor:
• Following is the form to use #define preprocessor to define
  a constant:
              #define identifier value
   Example
   #include <iostream>
   #define LENGTH 10
   #define WIDTH 5
   #define NEWLINE '\n'
   int main()
      {        int area;
               area = LENGTH * WIDTH;
               cout << area;
               cout << NEWLINE;
               return 0;
      }
                                         Result: 50
               The const Keyword:
• use const prefix to declare constants with a specific type as
  follows:
       const type variable = value;
   Example:-
   #include <iostream.h>
   int main()
   {
       const int LENGTH = 10;
       const int WIDTH = 5;
       const char NEWLINE = '\n';
       int area;
       area = LENGTH * WIDTH;
       cout << area;
       cout << NEWLINE;
       return 0;
                                            Output:50
   }
           Reference Variable
• Variable name as a label attached to the
  variable's location in memory.
• Reference as a second label attached to that
  memory location.
• Access the contents of the variable through
  either the original variable name or the
  reference.
• Syntax:
     Data-type & reference name = variable name
• For example
              int i = 17;
• We can declare reference variables for i as follows.
              int& r = i;
  the & in this declaration is as reference.
• Read declaration as "r is an integer reference
  initialized to i"
                                 Example
#include <iostream>
int main ()
 {
    // declare simple variables
    int i; double d;                                            Output:
    // declare reference variables               Value of i : 5
    int& r = i;                                  Value of i reference : 5
    double& s = d;                               Value of d : 11.7
     i = 5;                                      Value of d reference : 11.7
    cout << "Value of i : " << i << endl;
    cout << "Value of i reference : " << r << endl;
    d = 11.7;
    cout << "Value of d : " << d << endl;
    cout << "Value of d reference : " << s << endl;
    return 0;
}
           Comments in C++
• Program comments are explanatory
  statements that you can include in the C++
  code that you write and helps anyone reading
  it's source code.
• C++ supports single-line and multi-line
  comments. All characters available inside any
  comment are ignored by C++ compiler.
• C++ comments start with /* and end with */.
  For example:
     /* This is a comment */
     /* C++ comments can also
     * span multiple lines
     */
• A comment can also start with //, extending to
  the end of the line.
• For example:
#include <iostream.h>
main()
  {
      cout << "Hello World"; // prints Hello World
       return 0;
  }

                            Output : Hello World
           Default Parameter
• C++ allows to call function without specifying
  all its arguments
• Functions assigns default value to parameter
  which does not have matching argument in
  function call
• Specified when function is declared
       Default parameter (Example)
Float amount(float principal, float period, float rate=0.15)
Default value 0.15 to parameter rate
Function call like
        value = amount (5000,7); //one parameter missing
Passes 0.15 to rate

Now,
     value =amount(5000,7,0.12) //no missing argument
Passes explicit value 0.12 to rate
#include<iostream.h>                      Output:
 #include<conio.h>                        Enter Length:6
int vol(int=1,int=2,int=3);               Enter width:5
main() {                                  Enter height: 9
 clrscr();                                Volume with no argument passed =6
 int length; int width; int height;       Volume with one argument passed=36
 int volume;
cout<<"\n Enter length = ";
cin>>length;
cout<<"\n Enter width = ";                           int vol(int l,int h,int w)
cin>>width;                                          {
cout<<"\n Enter heigth = ";                           return l*h*w;
cin>>height;                                         }
volume=vol();
cout<<"\n Volume with no argument passed ="<<volume;
volume=vol(length);
cout<<"\n Volume with one argument passed = "<<volume;
volume=vol(length,width);
getch();
return 0; }
               C++ Functions
• Set of program statements that can be
  processed independently.

• Like in other languages, called subroutines or
  procedures.
              Advantages …?
•   Elimination of redundant code
•   Easier debugging
•   Reduction in the Size of the code
•   Leads to reusability of the code
•   Achievement of Procedure Abstraction
          Function Prototype
• Is a declaration statement in program
• Syntax:
     Return type function name (parameter list);
                    Sample function

                       ame   Formal parameters
Return type Function n



   int add_int(int a, int b)
   {
     return(a+b);
   }                                       Fun
                                              ctio
                                                  n bo
                                                      dy
        Function Overloading
Multiple functions to share the same name with
     different signatures(types or numbers).



 int myfunc(int i)     int myfunc(int i, int j)
 {                     {
 return i;             return i*j;
 }                     }
                   Inline Functions
• Disadvantages of using function
   Every time a function is called, it take a lot of extra
    time in executing a series of instructions.
   In the following ways of execution it takes more
    time
     §   Jumping to the function
     §   Saving in Register.
     §   Pushing arguments into the stack.
     §   Returning to the calling function.
               Inline Functions
Inline functions are those whose function body is
inserted in place of the function call statement during
the compilation process.

• Syntax:
     inline returntype func_name(formal parameters)
               {
                  function body
               }
             Inline Functions
• Conditions for inline functions
  – Function should not have any return statement
  – Function should not be recursive
  – Function length should be small
  – Function should not contain static variable
                              Example
void main()
                                               #include<iostream.h>
{
                                               #include<conio.h>
         line obj;
         float val1,val2;
                                            class line
         clrscr();
                                            {
   cout<<"Enter two values:";
                                               public:
   cin>>val1>>val2;
                                               inline float mul(float x,float y)
   cout<<"\nMultiplication value is:“;
                                                      {
  cout<<obj.mul(val1,val2);
                                                              return(x*y);
   cout<<"\n\nCube value is:”;
                                                      }
                                               inline float cube(float x)
cout<<obj.cube(val1)<<"\t"<<obj.cube(val2);
                                                      {
       getch();
                                                              return(x*x*x);
}
                                                      }
                                            };
                   Inline Function
• Advantages
   Ø Shorter execution time
   Ø Does not require function calling overhead
   Ø Saves time

• Disadvantages
   ØIncreases the length of file
   ØMay make our file unreadable
            C++ Overview




3/12/2020    Santosh A. Darade, SITS, Narhe   64
            Structure of C++ Program


                       Include Files

                     Class Definition

                Class Function Definition

                 Main Function Program

3/12/2020            Santosh A. Darade, SITS, Narhe   65
            Simple C++ Program
  // Hello World program                             comment


  #include <iostream.h>                              Allows access to an I/O
                                                     library

  int main() {
                                    Starts definition of special function
                                    main()
      cout << "Hello World\n";
                                                           output (print) a
                                                           string
      return 0;
                                            Program returns a status
  }                                         code (0 means OK)


3/12/2020           Santosh A. Darade, SITS, Narhe                        66
                       >> :- Input using Extraction operator




3/12/2020   Santosh A. Darade, SITS, Narhe                     67
                                                               C++




            Output using insertion
                  operator


3/12/2020                     Santosh A. Darade, SITS, Narhe         68
3/12/2020   Santosh A. Darade, SITS, Narhe   69
3/12/2020   Santosh A. Darade, SITS, Narhe   70
   Memory Management Operator
• New and delete operators are used to allocate
  and free the memory
• Object can be created by using new and
  deleted by using delete operator
• Syntax:
     Pointer variable = new data-type



3/12/2020         Santosh A. Darade, SITS, Narhe   71
                     Example
Int *p=new int;
Float *q=new float;
• Suppose
            *p=25
            *q=7.5




3/12/2020            Santosh A. Darade, SITS, Narhe   72
• Data object no longer needed, it is destroyed
  to release memory space for reuse.
• Syntax
            delete pointer variable

             Example :
                          delete q;
                          delete p;




3/12/2020                    Santosh A. Darade, SITS, Narhe   73
            Defining Class




3/12/2020      Santosh A. Darade, SITS, Narhe   74
               Class Specification
• Syntax:
  class class_name
   {

              Data members

            Members functions
    };

3/12/2020            Santosh A. Darade, SITS, Narhe   75
            Class Specification
• class Student
   {
     int st_id;                       Data Members or Properties of
                                      Student Class
     char st_name[];
     void read_data();                   Members Functions or
                                         Behaviours of Student Class
     void print_data();
  };

3/12/2020           Santosh A. Darade, SITS, Narhe                 76
                Class Specification
• Visibility of Data members & Member functions

   Public –
            Accessed by member functions and all other non-
            member functions in the program.
   Private –
            Accessed by only member functions of the class.
   Protected –
            Similar to private, but accessed by all the member
            functions of immediate derived class
   Default –
            All items defined in the class are private.


 3/12/2020                Santosh A. Darade, SITS, Narhe         77
            Class Specification
• class Student
   {
     int st_id;
     char st_name[];                                 private / default
     void read_data();                               visibility
     void print_data();
  };

3/12/2020           Santosh A. Darade, SITS, Narhe                  78
             Class Specification
• class Student
   {
     public:
       int st_id;
       char st_name[];
                                                      public visibility
     public:
        void read_data();
        void print_data();
  };


3/12/2020            Santosh A. Darade, SITS, Narhe                       79
                    Class Objects
• Object Instantiation:
    The process of creating object of the type class
• Syntax:
   class_name obj_name;                                   of the
                                                 bj e c t
                                       s ingle o
   ex: Student st;        Crea t e s
                             e Stude
                                     a
                                        nt!
                                           typ


                St_id, St_name

               void read_data( )

               void print_data( )
3/12/2020                 Santosh A. Darade, SITS, Narhe     80
               Class Object
• More of Objects
  ex: Student st1;
      Student st2;
      Student st3;




3/12/2020        Santosh A. Darade, SITS, Narhe   81
                           Class Objects

            10,Rama                                       20, Stephen

      void read_data( )                               void read_data( )

      void print_data( )                              void print_data( )


                st1                                               st2
                           55, Mary

                       void read_data( )

                       void print_data( )


3/12/2020                       st3
                                 Santosh A. Darade, SITS, Narhe            82
            Arrays of Objects
• Several objects of the same class can be
  declared as an array and used just like an array
  of any other data type.

• The syntax for declaring and using an object
  array is exactly the same as it is for any other
  type of array.


3/12/2020          Santosh A. Darade, SITS, Narhe    83
            33, Joseph
                         Class Objects                      St[0]
• Array     of )
  void read_data(                    Objects                S[0]
   ex:print_data( )                Student s[8];            S[1]
  void
                                                            S[2]
            24, Sakshi                                      S[3]
    void read_data( )
                                                            S[4]
                                                            S[5]
    void print_data( )
                                                            S[6]
                 St[4]                                      S[7]
3/12/2020                  Santosh A. Darade, SITS, Narhe           84
            Accessing Data Members
                 (inside the class)
• Syntax: (single object)
      data_member;
  ex: st_id;

• Syntax:(array of objects)
      data_member;
  ex: st_id;

3/12/2020          Santosh A. Darade, SITS, Narhe   85
            Accessing Data Members
                       (outside the class)
• Syntax: (single object)

    obj_name     . datamember;
    ex: st.st_id;

• Syntax:(array of objects)

    obj_name[i]     . datamember;
    ex: st[i].st_id;
3/12/2020                Santosh A. Darade, SITS, Narhe   86
            Defining Member Functions
                 (Inside the class definition)

• Syntax
  ret_type fun_name(formal parameters)
  {
     function body
  }




3/12/2020              Santosh A. Darade, SITS, Narhe   87
             Defining Member Functions
                 (Outside the class definition)

• Syntax
  ret_type class_name::fun_name(formal parameters)
  {
     function body
  }




 3/12/2020             Santosh A. Darade, SITS, Narhe   88
        Accessing Member Functions
• Syntax: (single object)

    obj_name     . Memberfunction(act_parameters);
    ex: st.read( );

• Syntax:(array of objects)

    obj_name[i]    . Memberfunction(act_parameters);
    ex: st[i].read( );
3/12/2020                Santosh A. Darade, SITS, Narhe   89
            Inline Functions with Class
• Syntax: (Inside the class definition)
  inline ret_type fun_name(formal parameters)
  {
      function body
  }




3/12/2020            Santosh A. Darade, SITS, Narhe   90
            Inline Functions with Class
• Syntax: (Outside the class definition)
  inline ret_type class_name::fun_name (formal
  parameters)
  {
      function body
  }



3/12/2020            Santosh A. Darade, SITS, Narhe   91
            Static Data Members
• Static data members of a class are also known
  as "class variables“.

• Because their content does not depend on
  any object.

• They have only one unique value for all the
  objects of that same class.
3/12/2020         Santosh A. Darade, SITS, Narhe   92
            Static Data Members
• Tells the compiler that only one copy of the
  variable will exist and all objects of the class
  will share that variable.

• Static variables are initialized to zero before
  the first object is created.

• Static members have the same properties as
  global variables but they enjoy class scope.
3/12/2020           Santosh A. Darade, SITS, Narhe   93
            Static Member Functions
• Member functions that are declared with
  static specifier.

      Syntax:
      class class_name
      {
      public:
      static ret_dt fun_name(formal parameters);
      };

3/12/2020            Santosh A. Darade, SITS, Narhe   94
             Static Member Functions
Special features:
• They can directly refer to static members of
  the class.
• They can be called using class name like..
            • Class name::function name;




3/12/2020                   Santosh A. Darade, SITS, Narhe   95
                              int main()
                              {
#include < iostream>
                              test t1,t2;
Class test
                              t1.setcode();
{
                              t2.setcode();
Int code;
                              test::showcount();
Static int count;
                              test t3;
Public:
                              t3.setcode();
Void setcode(void)
                              test::showcount();
{ code=++count;}
                              t1.showcode();
Void showcode(void)
                              t2.showcode();
{ cout<<“object no.:”<<code;}
                              t3.showcode();     Output
Static void showcount(void)
                              Return 0;          Count:2
{ cout<<“count:”<<count; }
                              }                  Count :3
};
Int test::count;                                 Object number:1
                                                 Object number:2
                                                 Object number:3
  3/12/2020              Santosh A. Darade, SITS, Narhe       96
              Constructors
• A constructor function is a special member
  function that is a member of a class and has
  the same name as that class, used to create,
  and initialize objects of the class.
• Constructor function do not have return type.
• Should be declared in public section.
• Invoked automatically when objects are
  created

3/12/2020        Santosh A. Darade, SITS, Narhe   97
               Constructors
Syntax:                                 Example:
class class_name                        class student
{
                                        { int st_id;
public:
class_name();                              public:
};                                            student()
                                              {
                                                 st_id=0;
                                              }
3/12/2020
                                        };
                   Santosh A. Darade, SITS, Narhe           98
                     Constructors
• How to call this special function…?
                                                        class student
                                                        {
    int main()                                                 int st_id;
    {                                                          public:
       student st;                                            student()
       …………                                                    {
       …………                                                       st_id=0;
    };                                                         }
3/12/2020              Santosh A. Darade, SITS, Narhe   };                   99
            Types of Constructors
•   Parameterized constructors
•   Constructors with default argument
•   Copy constructors
•   Dynamic constructors




3/12/2020          Santosh A. Darade, SITS, Narhe   100
               Parameterized Constructors
class Addition
{
                                                                   eters
      int num1;                Cons   t r u c to r with p
                                                        f u
                                                           a
                                                           n
                                                             r a m
                                                              ction!
                                                    o a
                                          it’s als
      int num2;                B ’ C o z

      int res;
      public:
      Addition(int a, int b); // constructor
      void add( );
      void print();         Constructor that can take
};                              arguments is called
   3/12/2020
                           parameterized constructor.
                            Santosh A. Darade, SITS, Narhe         101
             Overloaded Constructors
class Addition
{
     int num1,num2,res;                                                                ith
                                                                          r u c t or w
                                                                   Const
     float num3, num4, f_res; Over                    l o a d e d
                                                                     ’C oz t h ey are
                                                            ters B
                                              parame              ions!
     public:                                   also      fu n c t

     Addition(int a, int b); // int constructor
     Addition(float m, float n); //float constructor
     void add_int( );
     void add_float();
     void print();
};
3/12/2020                 Santosh A. Darade, SITS, Narhe                                     102
  Constructors with Default Argument
class Addition
{
      int num1;                     cto r w it h default
                            Constru
      int num2;             parame
                                   ter.

      int res;
      public:
      Addition(int a, int b=0); // constructor
      void add( );
      void print();
};
3/12/2020               Santosh A. Darade, SITS, Narhe     103
                    Copy Constructor
class code
                                       int main()
{                                      { code A(100);
        int id;                           code B(A);
        public:                           code C=A;
        code() //constructor              code D;
                                          D=A; // wrong syntax for copy
        { id=100;}
                                       construcor
        code(code &obj) // constructor cout<<“ id of A:”;    A.display();
        {                                 cout<<“ id of B:”;  B.display();
        id=obj.id;                        cout<<“ id of C:”;  C.display();
        }                                cout<<“ id of D:”;   D.display();
                                       }
        void display()    Copy constructor is used
        {
              cout<<id;   to declare and initialize
          }               an object from another
};                                    object
   3/12/2020                 Santosh A. Darade, SITS, Narhe          104
             Dynamic Constructors
Used to allocate memory at the time of object
                  creation

          class Sum_Array
          {
                 int *p;
                 public:
                 Sum_Array(int sz) // constructor
                 {
                 p=new int[sz];
                 }
3/12/2020
          };              Santosh A. Darade, SITS, Narhe   105
                     Destructors
• A destructor function is a special function that
  is a member of a class and has the same name
  as that class used to destroy the objects.
• Must be declared in public section.
• Destructor do not have arguments & return
  type.


            NOTE:
            A class can have ONLY ONE destructor
3/12/2020              Santosh A. Darade, SITS, Narhe   106
                   Destructors
Synatax:                            Example:
class class_name                    class student
{                                   {
public:                                   public:
~class_name();                           ~student()
};                                        {
                                            cout<<“Destructor”;
                                          }
                                    };


3/12/2020           Santosh A. Darade, SITS, Narhe           107
                           Local Classes
  • A class defined within a function is called
    Local Class.
                                          void fun()
Syntax:                                   {
void function()                                class myclass {
{                                                  int i;
  class class_name                                 public:
  {                                                void put_i(int n) { i=n; }
        // class definition                        int get_i() { return i; }
   } obj;                                          } ob;
  //function body                         ob.put_i(10);
}                                         cout << ob.get_i();
  3/12/2020
                                          }
                            Santosh A. Darade, SITS, Narhe                   108
              Multiple Classes
Synatax:             Example:                         Example:
class class_name1    class test                       class student
                     {                                {      int st_id;
{                      public:                               test m;
//class definition     int t[3];                             public:
};                   };                                  viod init_test()
                                                             {
class class_name2
                                                              m.t[0]=25;
{                                                             m.t[1]=22;
//class definition                                            m.t[2]=24;
};                                                           }
3/12/2020            Santosh A. Darade, SITS, Narhe   };              109
                   Nested Classes
Synatax:                              Example:
                                      class student
class outer_class                     {           int st_id;
{                                                 public:
  //class definition                              class dob
                                                     { public:
    class inner_class                                 int dd,mm,yy;
    {                                               }dt;
                                                void read()
       //class definition                         {
     };                                              dt.dd=25;
                                                    dt.mm=2;
                                                      dt.yy=1988;}
};                                    };
     3/12/2020          Santosh A. Darade, SITS, Narhe                110
            Friend Functions
• Friend function is a non-member function
  which can access the private members of a
  class

• To declare a friend function, its prototype
  should be included within the class, preceding
  it with the keyword friend.


3/12/2020         Santosh A. Darade, SITS, Narhe   111
             Friend Functions
                   Example:
                   class myclass
                    {
Syntax:               int a, b;
class class_name      public:
{                     friend int sum(myclass x);
//class definition    void set_val(int i, int j);
public:            };
friend rdt fun_name(formal parameters);
};
3/12/2020          Santosh A. Darade, SITS, Narhe   112
             Friend Function
• Characteristics:
• Not in the scope of class to which it has been
  declared as friend
• It can not be called using object of class
• Invoked like normal function
• Can not access data members directly, has to
  use object and dot operator
• Can be declare in private or public section.
• It has objects as arguments.
3/12/2020         Santosh A. Darade, SITS, Narhe   113
                                      Void max (XYZ m,ABC
#include<iostream>                    n)
Class ABC;                            {
Class XYZ                             If(m.x>=n.a)
{ int x;                              Cout<<m.x;
Public:                               Else
Void setvalue(int i) {x=i;}           Cout<<n.a;
Friend void max(XYZ,ABC);             }                        Output
};                                    Int main()                 20
Class ABC                             {
{ int a;                              ABC h;
Public:                               h.setvalue(10);
Void setvalue(int i) {a=i;}           XYZ j;
Friend void max(XYZ,ABC);             j.setvalue(20);
};                                    Max(h,j)
                                      }
  3/12/2020                   Santosh A. Darade, SITS, Narhe       114
            Pointers to Objects
       student st;                                   51, Rajesh

       student *ptr;                   void read_data( )

        ptr = & st;                    void print_data( )


                                                  st
              ptr                               2FCD54
3/12/2020           Santosh A. Darade, SITS, Narhe                115
                     Pointers to Objects
• Pointers can be defined to hold the address of an
  object, which is created statically or dynamically

                                      Statically created object:
        33, Joseph
                                      student      *stp;
                                      stp = &st;
    void read_data( )
                                      Dynamically created object:
    void print_data( )
                                      student *stp;
                                      stp = new student;
               st
3/12/2020
            2FCDA4        Santosh A. Darade, SITS, Narhe           116
             Pointers to Objects
• Accessing Members of objects:
   Syntax:
   ptr_ob j  member_name;
   ptr_obj  memberfunction_name( );

       Example:
       stp       st_name;
       stp       read_data ( );


3/12/2020           Santosh A. Darade, SITS, Narhe   117
             The this Pointer
• The this pointer points to the object that
  invoked the function

• When a member function is called with an
  object, it is automatically passed an implicit
  argument that is a pointer to the invoking
  object (that is, the object on which the
  function is called).

3/12/2020          Santosh A. Darade, SITS, Narhe   118
                 The this Pointer
• Accessing Members of objects:
   Syntax:
   obj . memberfunction_name( );

                            this pointer points to st object
       Example:
       st . read_data ( );



3/12/2020             Santosh A. Darade, SITS, Narhe       119
            Pointer to Class Member
• A special type of pointer that "points“
  generically to a member of a class, not to a
  specific instance of that member in an object

• Pointer to a class member is also called
  pointer-to-member.



3/12/2020          Santosh A. Darade, SITS, Narhe   120
            Pointer to Class Member
• It provides only an offset into an object of the
  member's class at which that member can be
  found.

• Member pointers are not true pointers, the . and
  -> cannot be applied to them.

• A pointer to a member is not the same as a
  normal C++ pointer.

3/12/2020          Santosh A. Darade, SITS, Narhe   121
             Pointer to Class Member
• To access a member of a class:
   Special pointer-to-member operators
            1) .*
            2) –>*




3/12/2020            Santosh A. Darade, SITS, Narhe   122
              Pointer to Class Member
• Syntax to create pointer to data member
  of a class:
               Data_type class_name ::* data_member_ptr;
               int student::*d_ptr;


• Syntax to create pointer to member function
  of a class:
               rtn_dt (class_name::* mem_func_ptr)(arguments);
               int (student::*f_ptr)();

  3/12/2020              Santosh A. Darade, SITS, Narhe    123
            Thank you




3/12/2020     Santosh A. Darade, SITS, Narhe   124
March 12, 2020
Tags

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget