SlideShare a Scribd company logo
1 of 80
Subject Name - C++
       Semester - II




                         Neetu Gupta

1
Contents
•   Arrays
•   Multidimensional Arrays
•   Pointers
•   Classes – A simple class
•   Inline member function
•   Constructor
•   Destructor
•   Member initialization list
•   Const members
Contents
•   static members
•   member pointers
•   Class object
•   Object arrays
Arrays
•   An array is a series of elements of the same type placed in contiguous memory
    locations that can be individually referenced by adding an index to a unique identifier.

•   That means that, for example, we can store 5 values of type int in an array without
    having to declare 5 different variables, each one with a different identifier. Instead of
    that, using an array we can store 5 different values of the same type, int for example,
    with a unique identifier.
    For example, an array to contain 5 integer values of type int called billy could be
    represented like this:




•   where each blank panel represents an element of the array, that in this case are
    integer values of type int. These elements are numbered from 0 to 4 since in arrays
    the first index is always 0, independently of its length.
Array - Declaration
• Like a regular variable, an array must be declared before
  it is used. A typical declaration for an array in C++ is:

             type name [elements];

  where type is a valid type (like int, float...),
  name is a valid identifier and the elements field (which is
  always enclosed in square brackets []), specifies how
  many of these elements the array has to contain.
• Therefore, in order to declare an array called billy as the
  one shown in the above diagram it is as simple as:

              int billy [5];

• The elements field within brackets [] which represents
  the number of elements the array is going to hold, must
  be a constant value, since arrays are blocks of non-
  dynamic memory whose size must be determined before
  execution. In order to create arrays with a variable length
  dynamic memory is needed, which is explained later in
  these tutorials.
Initializing arrays.

• When declaring a regular array of local scope
  (within a function, for example), if we do not
  specify otherwise, its elements will not be
  initialized to any value by default,
• In both cases, local and global, when we declare
  an array, we have the possibility to assign initial
  values to each one of its elements by enclosing
  the values in braces { }.
• For example:
        int billy [5] = { 16, 2, 77, 40, 12071 };
   This declaration would have created an array like this:




• When an initialization of values is provided for an array, C++ allows
  the possibility of leaving the square brackets empty [ ]. In this case,
  the compiler will assume a size for the array that matches the
  number of values included between braces { }:
         int billy [] = { 16, 2, 77, 40, 12071 };
   After this declaration, array billy would be 5 ints long, since we have
   provided 5 initialization values.
Accessing Array Values
• we can access the value of any of its elements individually as if it
  was a normal variable, thus being able to both read and modify its
  value. The format is as simple as:

                array-name [index]

• For example, to store the value 75 in the third element of billy, we
  could write the following statement:
                billy[2] = 75;

• For example, to store the value 75 in the third element of billy, we
  could write the following statement:
                billy[2] = 75;
• // arrays example
#include <iostream>
using namespace std;
int x [] = {2,3,4,5,6};
int n,
result=0;
int main () {
    for ( n=0 ; n<5 ; n++ ) {
          result += x [n];
    }
    cout << “Sum of array elements is: “ << result;
    return 0;
}

Output is:
   Sum of array elements is: 20
Multidimensional Arrays
• Multidimensional arrays can be described as
  "arrays of arrays".
• For example, a bidimensional array can be
  imagined as a bidimensional table made of
  elements, all of them of a same uniform data
  type.
• Here, jimmy represents a bidimensional array of
  3 per 5 elements of type int.
Multidimensional Arrays
• The way to declare this array in C++
  would be:
      int jimmy [3][5];
• the way to reference the second element
  vertically and fourth horizontally in an
  expression would be:
  jimmy[1][3]
Pointers
• Pointers are variables those store the
  address of any other variable.
• The value saved into a pointer type
  variable is interpreted as memory address.
• We can say that pointer is like any other
  variable but the value it stores is the
  address of some other variable
Pointer declaration
• We can delare a pointer as
      type *<name of pointer type variable>
• Example
      int *iptr;  // poniter to int type variable
      char *iptr; // poniter to char type variable
      double *iptr;     // poniter to double type
  variable
Address Operator – Pointer
            initialization
• We can initialize a pointer variable with
  address of a variable with the help of &
  operator
• Be careful about the data types. We can
  initialize a pointer to int type with the
  address of an int type variable only. The
  same applies to all other data types
I at 4000     iptr

   int i, *iptr




     Iptr = &i;                    Address of x
                                   i.e. 4000


    i = 40        40               Address of x
                                   i.e. 4000


• Once we change the value of i, the
  address in iptr will remain unchanged but
  the value pointed by iptr will also become
  same as i.
• Usually, pointer variables hold address to
  a specific kinds of data (e.g.: address of
  an int, address of a char, etc)

   int * p; /* variablep can hold the address of a memory location
                that contains an int */

   char * chptr; /* chptr can hold the address of a memory
                location that contains achar */

p and chptr both are pointers and can store addresses but p can only
   store address of a variable which is int and chptr can store address
   of a variable which is of char type.
Dereferencing Operator
• We can use the value of variable that a
  pointer points to with the help of *
  operator. Here,* is called the
  dereferencing operator
• The expression *p denotes the value of
  memory cell to which p points
• Be careful not to dereference a pointer
  that has not yet been initialized.
int i =10;
int * iptr = &10; // Initialize a pointer with an
                  address
                                   *p will be 10
                                   p will be 2000 i.e.
  i = 10          iptr = 2000      the address value
                                   at which I is
      2000                         stored in memory


Here i is an int variable store at location
 2000 in memory
Pointer arithmetic
• To conduct arithmetical operations on
  pointers is a little different than to conduct
  them on regular integer data types.
• Only addition and subtraction operations
  are allowed to be conducted with them
• Assume that in a given compiler for a
  specific machine, char takes 1 byte, short
  takes 2 bytes and long takes 4
• Suppose that we define three pointers in this
  compiler and they point to memory location
  1000, 2000, 3000 respectively:
           char *mychar;
           short *myshort;
           long *mylong;
• If we write the code as:
           mychar++;
           myshort++;
           mylong++;
• When mychar is incremented it is incremented by value
  1 i.e. size of char
• When myshort is incremented it is incremented by value
  2 i.e. size of short type
• When mylong is incremented it is incremented by value 4
  i.e. size of long type
• The same is applied to ++ or – operator.
• A pointer is incremented or decremented
  as much as the size of type it holds

     short s1 ,
     short *sptr = &sptr;
     sptr = sptr+2.

  Here if spr is 1000 initially it will be 1004 after
   adding two. As the size of one short is 2. Ans
   we are adding 2 that means 2*size of short
   type i.e. 4 now.
Classes
• A user defined data type
• It can hold both
      the data and
      the functions that operates on data.
• The elements in class – data & functions
  are called members of the class
class syntax
• Classes in C++ can be declared using the
  keyword class, with format:

  class class_name {
          access_specifier_1:
                       member1;
          access_specifier_2:
                       member2; ...
     };


  Here class_name is a valid identifier for the class,
• The body of the declaration can contain
  members, that can be either data or
  function declarations, and optionally
  access specifiers.
• We can also declare a variable of class
  type, such a variable is called object of
  that class

     class-type object-name;
// Class Rectangle - classes example
#include <iostream>
using namespace std;
class Rectangle {
     public:
       int x, y;
       void set_values (int , int);
       int area () {
         return (x*y);
       }
};

void Rectangle::set_values (int a, int b) {
   x = a;
  y = b;
}
• Declares a class (i.e., a user-defined type) called
  Rectangle.

• This class contains four members:
   – two data members of type int (member x and member
     y) with private access (because private is the default
     access level) and
   – two member functions with public access:
     set_values() and area()
   – The most important new thing in this code is the
     operator of scope (::, two colons) included in the
     definition of set_values(). It is used to define a
     member of a class from outside the class definition
     itself.
• We can declare a variable of type
  Rectangle as

      Rectangle rect1, rect2


  Here, rect1 and rect2 are two objects of type
   Rectangle.
Access member variable (.)
• After the previous declarations of Rectangle and
  rect1, we can refer within the body of the
  program to any of the public members of the
  object rect1 as if they were normal functions or
  normal variables, just by putting the object's
  name followed by a dot (.) and then the name of
  the member.
           rect1.set_values (3,4);
           myarea = rect1.area();
// Rectangle – Class Example
#include <iostream>
using namespace std;
class Rectangle {
    int x, y;
    public:
            void set_values (int,int);
            int area () {return (x*y);}
 };

void Rectangle::set_values (int a, int b) {
    x = a; y = b;
}

int main () {
    Rectangle rect; // Object of type Rectangle
    rect.set_values (3,4);
    cout << "area: " << rect.area();
    return 0;
}
Explanation of the previous programme

• The most important new thing in this code is the operator of scope
  (::, two colons) included in the definition of set_values(). It is used to
  define a member of a class from outside the class definition itself.
• You may notice that the definition of the member function area() has
  been included directly within the definition of the Rectangleclass
  given its extreme simplicity, whereas set_values() has only its
  prototype declared within the class, but its definition is outside it. In
  this outside declaration, we must use the operator of scope (::) to
  specify that we are defining a function that is a member of the class
  Rectangleand not a regular global function.
• The only difference between defining a class member function
  completely within its class or to include only the prototype and later
  its definition, is that in the first case the function will automatically be
  considered an inline member function by the compiler, while in the
  second it will be a normal (not-inline) class member function, which
  in fact supposes no difference in behavior.
Access specifiers
• Access specifier of a class member decides
  where that member can be used or not used.
• These specifiers modify the access rights that
  the members following them acquire:

      private
      protected
      public
• If we do not specify any access specifier while
  declaring it, then default access specifier is
  private.
•   private members of a class are
    accessible only from within other
    members of the same class or from their
    friends.
•   protected members are accessible from
    members of their same class and from
    their friends, but also from members of
    their derived classes.
•   public members are accessible from
    anywhere where the object is visible.
class Rectangle {
     int x, y;
     public:
           void set_values (int,int);
           int area (void);
}
• Here, no specifier is associated with
  members x and y, so these are private
• Both the member functions are declared
  as public
• If we have a program as below:
int main () {
   Rectangle rect;        // Object of type
   rect.x = 3;            // Error
   rect.y = 4      // Error
   rect.set_values (3,4);
   cout << "area: " << rect.area();
   return 0;
}

We can not access x, y in main function as these
 are declared as private in class Rectangle.
Constructor
• Objects generally need to initialize variables or
  assign dynamic memory during their process of
  creation
• Like in class we used a function set_values() to
  set the values of class variables x and y.
• what would happen if in the previous example
  we called the member function area() before
  having called function set_values()?
• We can avoid such situations with the use of
  special function called constructor.
Constructor
• A member function in a class which is
  automatically called whenever a new
  object of this class is created.
• Rules are :
  1. This constructor function must have the
     same name as the class,
  2. and cannot have any return type; not even
     void.
// Rectangle – Class Example
#include <iostream>
using namespace std;
class Rectangle {
    int x, y;
    public:
           Rectangle (int , int);      // constructor declaration
           int area () {return (x*y);}
 };

// Definition of constructor
Rectangle::Rectangle (int a, int b) {
    width = a;
    height = b;
}
In the example, class Rectangle has a
  member function with name Rectangle
• This is the constructor of class Rectangle.
• Note that the function has no return type –
  not even void
Constructors call
• A constructor gets automatically called
  when the object of class is created.
           Rectangle rect(10,20)
Here, the constructor provided in class will
  get called and the values 10,20 will get
  passed to variables x and y.
int main () {
  Rectanglerect1 (3,4);
  Rectangle rect2 (5,6);
  cout << "rect1 area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
Here, two objects of type Rectangle is created with
  the use of constructor.
• For rect1 constructor is called with parameter
  values are 3,4.
• For rect2 constructor is called with parameter
  values are 5,6.
Default Constructor
• If you do not declare any constructors in a class
  definition, the compiler adds to the class a default
  constructor with no arguments.
• Therefore, if you declare a class like this:
   class Rectangle {
       int x, y;
       public:
         int area () {
                  return (x*y);
         }
    };

The compiler assumes that Rectangle has a default
  constructor with no arguments
• You can declare objects of this class by
  simply declaring them without any
  arguments:

          Rectangle rect1;

• Here, the compiler calls the default
  constructor with no arguments even
  though we have not added any
  constructor into the class Rectangle.
Remember
• If you declare your own constructor for a
  class, the compiler no longer provides a
  default constructor.
• In that case, we you need to have a
  constructor with no arguments, then you
  have to write that explicitly into the class.
• If the Rectangle class has a constructor as
   class Rectangle {
        int x, y;
        public:
          Rectangle (int , int);   // constructor declaration
          int area () {
                   return (x*y);
          }
     };

Here
This code will work
         Rectangle rect(10,10);            // Correct
But
         Rectangle rect;                   // Error
will not work
Destructor
• The destructor are opposite to
  constrcutors in functinality
• It is automatically called when an object is
  destroyed. An object is destroyed when
  – its scope of existence has finished
  – it is an object dynamically assigned and it is
    released using the operator delete
• The second code does not work because, the
  constructor that we defined has overrided the default
  constructor provided by compiler.
• If we need the default one also, we should provide that
  as well in the class as

           class Rectangle {
                int x, y;
                public:
              Rectangle (int , int);      // constructor declaration
              Rectangle ();               // Default constructor declaration

                       int area () {
                                 return (x*y);
                       }
              };
Destructor
• The destructor must have the same name
  as the class, but preceded with a tilde sign
  (~)
• A destructor must also return no value i.e.
  no return type

• A destructor must also have no
  parameters.
// example on constructors and destructors
#include <iostream>
using namespace std;
class Rectangle{
     int *width, *height;
public:
     Rectangle (int, int);
     ~Rectangle();        // Destructor declarartion
     int area () {
             return (*width * *height);
     }
};

Rectangle :: Rectangle (int a, int b) {
   width = new int;
   height = new int;
   *width = a;
   *height = b;
}

Rectangle ::~Rectangle() {        // Destructor definition
   cout << “ In destructor of Rectangle class n”;
   delete width;
   delete height;
}
• In the above example we declare a
  member function with name ~Rectangle();
• This is the destructor for the class
  Rectangle, which has no parameters and
  no return type
• We can use a destructor as below in a main() fucntion
  int main () {
       Rectangle rect (3,4);
       cout << "rect area: " << rectb.area();
       return 0;
}
Output is
        rect area: 12
       In destructor of class Rectangle.

• rect object is created and initialized with values 3,4.
• The destructor of this object is called when rect goes out
  of scope
Pointers to classes
• It is valid to create pointers that point to
  classes
• A class becomes a valid type, so we can
  use the class name as the type for the
  pointer
• For example we can have a pointer to an
  object of type Rectangle as
                Rectangle *rect;
• To use directly a member of an object
  pointed by a pointer we can use the arrow
  operator (->) of indirection.
• To use the members of class Rectangle
  using pointer
    Rectangle * rect;
    rect = new Rectangle (10,20);
    // calls the area() function on the object pointed by
    // pointer rect
             rect->area();
• We can create a new object and assign it
  to a pointer as
                Rectangle * rect = new Recatngle(10,20);

• We can assign the address of already created object to a newly
  declared pointer. For this we make use of the “address of” operator
  (&) as

                Rectangle rectObj(10,20);
                Rectangle rectPtr = &rectObj.
• // pointer to classes example
#include <iostream>
using namespace std;
class Rectangle {
   int width, height;
   public:
         void set_values (int, int);
         int area (void) {
                  return (width * height);
         }
   };

void Rectangle::set_values (int a, int b) {
   width = a;
   height = b;
}
int main () {
    Rectangle a, *b, *c;
    b= new Rectangle;
    c= &a;
    a.set_values (1,2);
    b->set_values (3,4);
    cout << "a area: " << a.area() << endl;
    cout << "*b area: " << b->area() << endl;
    cout << "*c area: " << c->area() << endl;
    delete b;
    return 0;
}

Output is
        a area: 2
        *b area: 12
        *c area: 2
Object Arrays
• The way we declare an array of simple
  data types, we can also declare an array
  of class type
• Here each element is an object of that
  class type and we can refer to it using []
  operator.
// Array of objects
int main () {
    Rectangle objR[5];
    // first element can be referd as objR[0]
    cout << “Area of first object is: “ << objR[0].area();
    cout << “Area of second object is: “ << objR[1].area();
    ………..
}

Here objR is an array of objects of type Rectangle. Each object can be
  used with name bjR followed by [], provided with an index value.
Summary
Expression          Meaning
*x           pointed by x

&x           Address of x

x.y          Member y of object x

x->y         Member y of object pointed
             by x
Static member
• When a member of class is declared as
  static it has a special different meaning
• A class can contain static members, either
  data or functions.
• There is only one copy of static member of
  a class which is being shared by all the
  objects of the class
• That is why we can also call the static
  members of a class as “class variable”.
• If you declare a variable without static, that
  means it is an instance variable.
• This means that every object will have its own
  copy of that variable.
• In example below any object of type Dummy will
  have its own copy
           class Dummy {
             int x, y;
             public:
             Dummy (int I, int j) {
                   x = i;
                   y = j;
             }
           }
• Here the variable count is declared static,
  it will be shared by all object like If we declare
  two object as
          int main () {
             Dummy a(10,20), b(100,200);
            return 0;
          }
• In this case objects will be as below. Objects a and b has
  its own copy of static member


         X = 10                   X = 100


       Y = 20                      Y = 200
         Object a                    Object b
• If we add a static member to class Dummy
        class Dummy {
                    int x, y;
                    static int count;
                    public:
                    Dummy (int I, int j) {
                            x = i;
                            y = j;
                            count++;
                    }
        }
        int Dummy::count = 0;

• we can only include the prototype (its declaration) in the class
  declaration but not its definition (its initialization). We should initialize
  a static data-member with a formal definition outside the class as
                int Dummy::count = 0;
X = 10              X = 100


       Y = 20               Y = 200
         Object a             Object b


                    count


• Here both the objects will point to a single
  copy of count variable.
class Dummy {               int main () {
   int x, y;
                                 Dummy a(10,20), b(100,200);
   static int count;
                                cout << “count in a ;” << a.count;
   public:
                                cout << “count in b ;” << b.count;
   Dummy (int I, int j) {
          x = i;                return 0;
          y = j;            }
          count++;
   }
}
int Dummy::count = 0;

       Output is
             count in a : 2
             count in b : 2
       Both the objects have same value
Static function
• Similarly we can declare a function as
  static.
• We should then call this function using
  operator :: with class name as
     class_name::static_member
// class with static member function
class Dummy {
     int x, y;
     static int count;
     public:
     Dummy (int I, int j) {
       x = i;
       y = j;
       count++;
     }
     static int getCount() {

     }
}
int Dummy::count = 0;
int main () {
    Dummy a(10,20), b(100,200);
   cout << “count in a ;” << Dummy::getCount();
   cout << “count in b ;” << Dummy::getCount();;
   return 0;
}


• Here notice the code Dummy::getCount();
  getCount() is a static function and it is called
  using the class name with operator ::
Constant Members function
• We can declare a function as const
  member function.
• A function declared as const can not alter
  any data member in the class
• A member function is declared as constant
  with the use of keyword const, prefixed
  with function prototype as
    const return_type function_name (parameters);
class Dummy {
      int x, y;
      public:
      Dummy (int I, int j) {
        x = i;
        y = j;
      }
      const int getX() {
                return x;
      }
      const int getY() {
                return y;
      }
}

• Here, the functions getX() and getY() should not modify any data,
  hence we declared them as constant.
• If we change the code of getX() or getY()
  as
        const int getX() {
            x= 10; // Compilation Error
            return x;
    }
• So declaring as function const is a
  message to compiler that this function
  should not modify any data in the
  class.
const member variable
• We can also declare a variable as const
  in a class
           const int id;
• That means once initialized with a value
  the content of variable id can not be
  changed.
Initializing const variable
• The only place to initialize a const variable is to initialize
  in the initialization list.
• As discussed before, initializing the value in the
  initialization list is not as same as assigning a value..
• If a class has two variables id (const) and age (non-
  const), then the initialization for these will be as
                  int id, age;
                  public:
                   Employee (int I, int j) : id (i) { // Initialize
                                age = j;        // Assignment
                  }
// class const variable member - Example
class Employee {
        const int id;
        int age;
        public:
            Employee (int I, int j) : id (i) { // Initialize
                          age = j; // Assignment
            }
          void set_values (int i, int j) {
            id = i;       // Compilation Error
            age = j;
          }
}

Here we can initialize the id in initialization list but can not assign it any
  value later in any other function as set_value() here.
Initialization list
• C++ provides a way of initializing member
  variables when they are created rather
  than afterwards using initialization list.
• The initialization list is inserted after the
  constructor parameters, begins with a
  colon (:), and then lists each variable to
  initialize along with the value for that
  variable separated by a comma.
• Take an example as below which do not
  use initialization list. It does explicit
  assignments in the constructor body
       class Rectangle {
         int width, height;
         public:
             Rectangle (int w, int h) {
                  width = w;
                  height = h;
             }
         };
• This assignment not initialization
• Now see the code using initialization list

        class Rectangle {
          int width, height;
          public:
              Rectangle (int w, int h) : width (w), height (h)
              {
              }
          };
  Here width and height are initialized using
   initialization list not using assighment.
Note that
• we no longer need to do the explicit
  assignments in the constructor body, since
  the initializer list replaces that functionality.
• the initialization list does not end in a
  semicolon.
Thank You




80

More Related Content

What's hot (20)

Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
C# String
C# StringC# String
C# String
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
Array
ArrayArray
Array
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Computer programming 2 Lesson 5
Computer programming 2  Lesson 5Computer programming 2  Lesson 5
Computer programming 2 Lesson 5
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Week06
Week06Week06
Week06
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
7array in c#
7array in c#7array in c#
7array in c#
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 

Similar to C96e1 session3 c++

C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfYRABHI
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programmingHarshita Yadav
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxsangeeta borde
 
Generative Coding Lecture notes using coding
Generative Coding Lecture notes using codingGenerative Coding Lecture notes using coding
Generative Coding Lecture notes using codingssuserff773c
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Welcome to our_presentation in c
Welcome to our_presentation in cWelcome to our_presentation in c
Welcome to our_presentation in cimran hasan
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART IHari Christian
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C languageMehwish Mehmood
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'eShikshak
 

Similar to C96e1 session3 c++ (20)

Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdf
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
Pointers
PointersPointers
Pointers
 
Data types
Data typesData types
Data types
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
Generative Coding Lecture notes using coding
Generative Coding Lecture notes using codingGenerative Coding Lecture notes using coding
Generative Coding Lecture notes using coding
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
java.pdf
java.pdfjava.pdf
java.pdf
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Welcome to our_presentation in c
Welcome to our_presentation in cWelcome to our_presentation in c
Welcome to our_presentation in c
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
 

More from Mukund Trivedi

More from Mukund Trivedi (20)

System development life cycle (sdlc)
System development life cycle (sdlc)System development life cycle (sdlc)
System development life cycle (sdlc)
 
Process of design
Process of designProcess of design
Process of design
 
New file and form 2
New file and form 2New file and form 2
New file and form 2
 
File organisation
File organisationFile organisation
File organisation
 
Evaluation
EvaluationEvaluation
Evaluation
 
Database
DatabaseDatabase
Database
 
Case tools
Case toolsCase tools
Case tools
 
Evaluation
EvaluationEvaluation
Evaluation
 
Dfd final
Dfd finalDfd final
Dfd final
 
Sad
SadSad
Sad
 
C++ file
C++ fileC++ file
C++ file
 
Ff40fnatural resources (1)
Ff40fnatural resources (1)Ff40fnatural resources (1)
Ff40fnatural resources (1)
 
Ff40fnatural resources
Ff40fnatural resourcesFf40fnatural resources
Ff40fnatural resources
 
F58fbnatural resources 2 (1)
F58fbnatural resources 2 (1)F58fbnatural resources 2 (1)
F58fbnatural resources 2 (1)
 
F58fbnatural resources 2
F58fbnatural resources 2F58fbnatural resources 2
F58fbnatural resources 2
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Ee2fbunit 7
Ee2fbunit 7Ee2fbunit 7
Ee2fbunit 7
 
E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)
 
E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)
 
E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2
 

Recently uploaded

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

C96e1 session3 c++

  • 1. Subject Name - C++ Semester - II Neetu Gupta 1
  • 2. Contents • Arrays • Multidimensional Arrays • Pointers • Classes – A simple class • Inline member function • Constructor • Destructor • Member initialization list • Const members
  • 3. Contents • static members • member pointers • Class object • Object arrays
  • 4. Arrays • An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. • That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier. For example, an array to contain 5 integer values of type int called billy could be represented like this: • where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.
  • 5. Array - Declaration • Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain.
  • 6. • Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as: int billy [5]; • The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non- dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.
  • 7. Initializing arrays. • When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, • In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }.
  • 8. • For example: int billy [5] = { 16, 2, 77, 40, 12071 }; This declaration would have created an array like this: • When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }: int billy [] = { 16, 2, 77, 40, 12071 }; After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.
  • 9. Accessing Array Values • we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as: array-name [index] • For example, to store the value 75 in the third element of billy, we could write the following statement: billy[2] = 75; • For example, to store the value 75 in the third element of billy, we could write the following statement: billy[2] = 75;
  • 10. • // arrays example #include <iostream> using namespace std; int x [] = {2,3,4,5,6}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += x [n]; } cout << “Sum of array elements is: “ << result; return 0; } Output is: Sum of array elements is: 20
  • 11. Multidimensional Arrays • Multidimensional arrays can be described as "arrays of arrays". • For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type. • Here, jimmy represents a bidimensional array of 3 per 5 elements of type int.
  • 12. Multidimensional Arrays • The way to declare this array in C++ would be: int jimmy [3][5]; • the way to reference the second element vertically and fourth horizontally in an expression would be: jimmy[1][3]
  • 13. Pointers • Pointers are variables those store the address of any other variable. • The value saved into a pointer type variable is interpreted as memory address. • We can say that pointer is like any other variable but the value it stores is the address of some other variable
  • 14. Pointer declaration • We can delare a pointer as type *<name of pointer type variable> • Example int *iptr; // poniter to int type variable char *iptr; // poniter to char type variable double *iptr; // poniter to double type variable
  • 15. Address Operator – Pointer initialization • We can initialize a pointer variable with address of a variable with the help of & operator • Be careful about the data types. We can initialize a pointer to int type with the address of an int type variable only. The same applies to all other data types
  • 16. I at 4000 iptr int i, *iptr Iptr = &i; Address of x i.e. 4000 i = 40 40 Address of x i.e. 4000 • Once we change the value of i, the address in iptr will remain unchanged but the value pointed by iptr will also become same as i.
  • 17. • Usually, pointer variables hold address to a specific kinds of data (e.g.: address of an int, address of a char, etc) int * p; /* variablep can hold the address of a memory location that contains an int */ char * chptr; /* chptr can hold the address of a memory location that contains achar */ p and chptr both are pointers and can store addresses but p can only store address of a variable which is int and chptr can store address of a variable which is of char type.
  • 18. Dereferencing Operator • We can use the value of variable that a pointer points to with the help of * operator. Here,* is called the dereferencing operator • The expression *p denotes the value of memory cell to which p points • Be careful not to dereference a pointer that has not yet been initialized.
  • 19. int i =10; int * iptr = &10; // Initialize a pointer with an address *p will be 10 p will be 2000 i.e. i = 10 iptr = 2000 the address value at which I is 2000 stored in memory Here i is an int variable store at location 2000 in memory
  • 20. Pointer arithmetic • To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types. • Only addition and subtraction operations are allowed to be conducted with them • Assume that in a given compiler for a specific machine, char takes 1 byte, short takes 2 bytes and long takes 4
  • 21. • Suppose that we define three pointers in this compiler and they point to memory location 1000, 2000, 3000 respectively: char *mychar; short *myshort; long *mylong; • If we write the code as: mychar++; myshort++; mylong++;
  • 22. • When mychar is incremented it is incremented by value 1 i.e. size of char • When myshort is incremented it is incremented by value 2 i.e. size of short type • When mylong is incremented it is incremented by value 4 i.e. size of long type
  • 23. • The same is applied to ++ or – operator. • A pointer is incremented or decremented as much as the size of type it holds short s1 , short *sptr = &sptr; sptr = sptr+2. Here if spr is 1000 initially it will be 1004 after adding two. As the size of one short is 2. Ans we are adding 2 that means 2*size of short type i.e. 4 now.
  • 24. Classes • A user defined data type • It can hold both the data and the functions that operates on data. • The elements in class – data & functions are called members of the class
  • 25. class syntax • Classes in C++ can be declared using the keyword class, with format: class class_name { access_specifier_1: member1; access_specifier_2: member2; ... }; Here class_name is a valid identifier for the class,
  • 26. • The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers. • We can also declare a variable of class type, such a variable is called object of that class class-type object-name;
  • 27. // Class Rectangle - classes example #include <iostream> using namespace std; class Rectangle { public: int x, y; void set_values (int , int); int area () { return (x*y); } }; void Rectangle::set_values (int a, int b) { x = a; y = b; }
  • 28. • Declares a class (i.e., a user-defined type) called Rectangle. • This class contains four members: – two data members of type int (member x and member y) with private access (because private is the default access level) and – two member functions with public access: set_values() and area() – The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself.
  • 29. • We can declare a variable of type Rectangle as Rectangle rect1, rect2 Here, rect1 and rect2 are two objects of type Rectangle.
  • 30. Access member variable (.) • After the previous declarations of Rectangle and rect1, we can refer within the body of the program to any of the public members of the object rect1 as if they were normal functions or normal variables, just by putting the object's name followed by a dot (.) and then the name of the member. rect1.set_values (3,4); myarea = rect1.area();
  • 31. // Rectangle – Class Example #include <iostream> using namespace std; class Rectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void Rectangle::set_values (int a, int b) { x = a; y = b; } int main () { Rectangle rect; // Object of type Rectangle rect.set_values (3,4); cout << "area: " << rect.area(); return 0; }
  • 32. Explanation of the previous programme • The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself. • You may notice that the definition of the member function area() has been included directly within the definition of the Rectangleclass given its extreme simplicity, whereas set_values() has only its prototype declared within the class, but its definition is outside it. In this outside declaration, we must use the operator of scope (::) to specify that we are defining a function that is a member of the class Rectangleand not a regular global function. • The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior.
  • 33. Access specifiers • Access specifier of a class member decides where that member can be used or not used. • These specifiers modify the access rights that the members following them acquire: private protected public • If we do not specify any access specifier while declaring it, then default access specifier is private.
  • 34. private members of a class are accessible only from within other members of the same class or from their friends. • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. • public members are accessible from anywhere where the object is visible.
  • 35. class Rectangle { int x, y; public: void set_values (int,int); int area (void); } • Here, no specifier is associated with members x and y, so these are private • Both the member functions are declared as public
  • 36. • If we have a program as below: int main () { Rectangle rect; // Object of type rect.x = 3; // Error rect.y = 4 // Error rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } We can not access x, y in main function as these are declared as private in class Rectangle.
  • 37. Constructor • Objects generally need to initialize variables or assign dynamic memory during their process of creation • Like in class we used a function set_values() to set the values of class variables x and y. • what would happen if in the previous example we called the member function area() before having called function set_values()? • We can avoid such situations with the use of special function called constructor.
  • 38. Constructor • A member function in a class which is automatically called whenever a new object of this class is created. • Rules are : 1. This constructor function must have the same name as the class, 2. and cannot have any return type; not even void.
  • 39. // Rectangle – Class Example #include <iostream> using namespace std; class Rectangle { int x, y; public: Rectangle (int , int); // constructor declaration int area () {return (x*y);} }; // Definition of constructor Rectangle::Rectangle (int a, int b) { width = a; height = b; }
  • 40. In the example, class Rectangle has a member function with name Rectangle • This is the constructor of class Rectangle. • Note that the function has no return type – not even void
  • 41. Constructors call • A constructor gets automatically called when the object of class is created. Rectangle rect(10,20) Here, the constructor provided in class will get called and the values 10,20 will get passed to variables x and y.
  • 42. int main () { Rectanglerect1 (3,4); Rectangle rect2 (5,6); cout << "rect1 area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Here, two objects of type Rectangle is created with the use of constructor. • For rect1 constructor is called with parameter values are 3,4. • For rect2 constructor is called with parameter values are 5,6.
  • 43. Default Constructor • If you do not declare any constructors in a class definition, the compiler adds to the class a default constructor with no arguments. • Therefore, if you declare a class like this: class Rectangle { int x, y; public: int area () { return (x*y); } }; The compiler assumes that Rectangle has a default constructor with no arguments
  • 44. • You can declare objects of this class by simply declaring them without any arguments: Rectangle rect1; • Here, the compiler calls the default constructor with no arguments even though we have not added any constructor into the class Rectangle.
  • 45. Remember • If you declare your own constructor for a class, the compiler no longer provides a default constructor. • In that case, we you need to have a constructor with no arguments, then you have to write that explicitly into the class.
  • 46. • If the Rectangle class has a constructor as class Rectangle { int x, y; public: Rectangle (int , int); // constructor declaration int area () { return (x*y); } }; Here This code will work Rectangle rect(10,10); // Correct But Rectangle rect; // Error will not work
  • 47. Destructor • The destructor are opposite to constrcutors in functinality • It is automatically called when an object is destroyed. An object is destroyed when – its scope of existence has finished – it is an object dynamically assigned and it is released using the operator delete
  • 48. • The second code does not work because, the constructor that we defined has overrided the default constructor provided by compiler. • If we need the default one also, we should provide that as well in the class as class Rectangle { int x, y; public: Rectangle (int , int); // constructor declaration Rectangle (); // Default constructor declaration int area () { return (x*y); } };
  • 49. Destructor • The destructor must have the same name as the class, but preceded with a tilde sign (~) • A destructor must also return no value i.e. no return type • A destructor must also have no parameters.
  • 50. // example on constructors and destructors #include <iostream> using namespace std; class Rectangle{ int *width, *height; public: Rectangle (int, int); ~Rectangle(); // Destructor declarartion int area () { return (*width * *height); } }; Rectangle :: Rectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } Rectangle ::~Rectangle() { // Destructor definition cout << “ In destructor of Rectangle class n”; delete width; delete height; }
  • 51. • In the above example we declare a member function with name ~Rectangle(); • This is the destructor for the class Rectangle, which has no parameters and no return type
  • 52. • We can use a destructor as below in a main() fucntion int main () { Rectangle rect (3,4); cout << "rect area: " << rectb.area(); return 0; } Output is rect area: 12 In destructor of class Rectangle. • rect object is created and initialized with values 3,4. • The destructor of this object is called when rect goes out of scope
  • 53. Pointers to classes • It is valid to create pointers that point to classes • A class becomes a valid type, so we can use the class name as the type for the pointer • For example we can have a pointer to an object of type Rectangle as Rectangle *rect;
  • 54. • To use directly a member of an object pointed by a pointer we can use the arrow operator (->) of indirection. • To use the members of class Rectangle using pointer Rectangle * rect; rect = new Rectangle (10,20); // calls the area() function on the object pointed by // pointer rect rect->area();
  • 55. • We can create a new object and assign it to a pointer as Rectangle * rect = new Recatngle(10,20); • We can assign the address of already created object to a newly declared pointer. For this we make use of the “address of” operator (&) as Rectangle rectObj(10,20); Rectangle rectPtr = &rectObj.
  • 56. • // pointer to classes example #include <iostream> using namespace std; class Rectangle { int width, height; public: void set_values (int, int); int area (void) { return (width * height); } }; void Rectangle::set_values (int a, int b) { width = a; height = b; }
  • 57. int main () { Rectangle a, *b, *c; b= new Rectangle; c= &a; a.set_values (1,2); b->set_values (3,4); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; delete b; return 0; } Output is a area: 2 *b area: 12 *c area: 2
  • 58. Object Arrays • The way we declare an array of simple data types, we can also declare an array of class type • Here each element is an object of that class type and we can refer to it using [] operator.
  • 59. // Array of objects int main () { Rectangle objR[5]; // first element can be referd as objR[0] cout << “Area of first object is: “ << objR[0].area(); cout << “Area of second object is: “ << objR[1].area(); ……….. } Here objR is an array of objects of type Rectangle. Each object can be used with name bjR followed by [], provided with an index value.
  • 60. Summary Expression Meaning *x pointed by x &x Address of x x.y Member y of object x x->y Member y of object pointed by x
  • 61. Static member • When a member of class is declared as static it has a special different meaning • A class can contain static members, either data or functions. • There is only one copy of static member of a class which is being shared by all the objects of the class • That is why we can also call the static members of a class as “class variable”.
  • 62. • If you declare a variable without static, that means it is an instance variable. • This means that every object will have its own copy of that variable. • In example below any object of type Dummy will have its own copy class Dummy { int x, y; public: Dummy (int I, int j) { x = i; y = j; } }
  • 63. • Here the variable count is declared static, it will be shared by all object like If we declare two object as int main () { Dummy a(10,20), b(100,200); return 0; } • In this case objects will be as below. Objects a and b has its own copy of static member X = 10 X = 100 Y = 20 Y = 200 Object a Object b
  • 64. • If we add a static member to class Dummy class Dummy { int x, y; static int count; public: Dummy (int I, int j) { x = i; y = j; count++; } } int Dummy::count = 0; • we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). We should initialize a static data-member with a formal definition outside the class as int Dummy::count = 0;
  • 65. X = 10 X = 100 Y = 20 Y = 200 Object a Object b count • Here both the objects will point to a single copy of count variable.
  • 66. class Dummy { int main () { int x, y; Dummy a(10,20), b(100,200); static int count; cout << “count in a ;” << a.count; public: cout << “count in b ;” << b.count; Dummy (int I, int j) { x = i; return 0; y = j; } count++; } } int Dummy::count = 0; Output is count in a : 2 count in b : 2 Both the objects have same value
  • 67. Static function • Similarly we can declare a function as static. • We should then call this function using operator :: with class name as class_name::static_member
  • 68. // class with static member function class Dummy { int x, y; static int count; public: Dummy (int I, int j) { x = i; y = j; count++; } static int getCount() { } } int Dummy::count = 0;
  • 69. int main () { Dummy a(10,20), b(100,200); cout << “count in a ;” << Dummy::getCount(); cout << “count in b ;” << Dummy::getCount();; return 0; } • Here notice the code Dummy::getCount(); getCount() is a static function and it is called using the class name with operator ::
  • 70. Constant Members function • We can declare a function as const member function. • A function declared as const can not alter any data member in the class • A member function is declared as constant with the use of keyword const, prefixed with function prototype as const return_type function_name (parameters);
  • 71. class Dummy { int x, y; public: Dummy (int I, int j) { x = i; y = j; } const int getX() { return x; } const int getY() { return y; } } • Here, the functions getX() and getY() should not modify any data, hence we declared them as constant.
  • 72. • If we change the code of getX() or getY() as const int getX() { x= 10; // Compilation Error return x; } • So declaring as function const is a message to compiler that this function should not modify any data in the class.
  • 73. const member variable • We can also declare a variable as const in a class const int id; • That means once initialized with a value the content of variable id can not be changed.
  • 74. Initializing const variable • The only place to initialize a const variable is to initialize in the initialization list. • As discussed before, initializing the value in the initialization list is not as same as assigning a value.. • If a class has two variables id (const) and age (non- const), then the initialization for these will be as int id, age; public: Employee (int I, int j) : id (i) { // Initialize age = j; // Assignment }
  • 75. // class const variable member - Example class Employee { const int id; int age; public: Employee (int I, int j) : id (i) { // Initialize age = j; // Assignment } void set_values (int i, int j) { id = i; // Compilation Error age = j; } } Here we can initialize the id in initialization list but can not assign it any value later in any other function as set_value() here.
  • 76. Initialization list • C++ provides a way of initializing member variables when they are created rather than afterwards using initialization list. • The initialization list is inserted after the constructor parameters, begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma.
  • 77. • Take an example as below which do not use initialization list. It does explicit assignments in the constructor body class Rectangle { int width, height; public: Rectangle (int w, int h) { width = w; height = h; } }; • This assignment not initialization
  • 78. • Now see the code using initialization list class Rectangle { int width, height; public: Rectangle (int w, int h) : width (w), height (h) { } }; Here width and height are initialized using initialization list not using assighment.
  • 79. Note that • we no longer need to do the explicit assignments in the constructor body, since the initializer list replaces that functionality. • the initialization list does not end in a semicolon.

Editor's Notes

  1. Amity Business School