Unit-04

Unit-04/Lecture-01

 

·         Container Classes

·         Container types

·         Typical functions and iterator methods

·         Heterogeneous containers

·         Persistent objects          

·         Stream and files

·         Object oriented programming language

 

Container Classes

 

·         A container is a class, a data structure or an abstract data type (ADT) whose instances are collections of other objects. In other words; they are used for storing objects in an organized way following specific access rules. The size of the container depends on the number of the objects (elements) it contains.

·         Container classes are an important category of ADTs { They are used to maintain collections of elements like stacks, queues, linked lists, tables, trees, etc. Container classes form the basis for various C++ class libraries .

·         A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows a great flexibility in the types supported as elements.

·         The containers are template classes that enable specification of objects that are allowed in the containers.

Containers can be studied under three points of views.

1.     Access : It means accessing the container elements. In the case of arrays, accessing is done with the array index. For stacks, access of elements is done using LIFO (Last In First Out) [3] (alternative name FILO (First In Last Out) and in queues it is done using FIFO (First In First Out).

2.     Storage : It includes storing of items of containers. Some containers are finite containers and some are infinite containers.

3.     Traversal : It includes how the item can be traversed.

 

 

Container classes are expected to implement methods to do the following:

·         create a new empty container (constructor),

·         report the number of objects it stores (size),

·         delete all the objects in the container (clear),

·         insert new objects into the container,

·         remove objects from it,

·         provide access to the stored objects.

 

Container Class Objectives

 

·         Application Independence

·         Ease of Modification

·         Ease of Manipulation

·         Type Safety

·         Run-Time Efficiency and Space Utilization.

Use a Container Pattern :

  • To represent any group of objects as a single entity.
  • To reuse the code to store different kinds of objects

 

 

 

 

 

 

 

 

 

 

 

Unit-04/Lecture-02

 


Containers in the STL can be divided into three categories: sequence containers, associative containers, and container adapters.

Sequence containers

·         Sequence containers maintain the ordering of inserted elements that you specify.

·         A vector container behaves like an array, but can automatically grow as required. It is random access and contiguously stored, and length is highly flexible. For these reasons and more, vector is the preferred sequence container for most applications

·         An array container has some of the strengths of vector, but the length is not as flexible.

·         A deque (double-ended queue) container allows for fast insertions and deletions at the beginning and end of the container. It shares the random-access and flexible-length advantages of vector, but is not contiguous.

·         A list container is a doubly linked list that enables bidirectional access, fast insertions, and fast deletions anywhere in the container, but you cannot randomly access an element in the container.

·         A forward_list container is a singly linked list—the forward-access version of list.

Associative Containers

In associative containers, elements are inserted in a pre-defined order—for example, as sorted ascending. Unordered associative containers are also available. The associative containers can be grouped into two subsets: maps and sets.

·         A map, sometimes referred to as a dictionary, consists of a key/value pair. The key is used to order the sequence, and the value is associated with that key.

·         A set is just an ascending container of unique elements—the value is also the key. The unordered version of set is unordered_set.

·         Both map and set only allow one instance of a key or element to be inserted into the container. If multiple instances of elements are required, use multimap or multiset. The unordered versions are unordered_multimap and unordered_multiset.

 

Container Adapters.

A container adapter is a variation of a sequence or associative container that restricts the interface for simplicity and clarity. Container adapters do not support iterators.

·         A queue container follows FIFO (first in, first out) semantics. The first element pushed—that is, inserted into the queue—is the first to be popped—that is, removed from the queue.

·         A priority_queue container is organized such that the element that has the highest value is always first in the queue.

·         A stack container follows LIFO (last in, first out) semantics. The last element pushed on the stack is the first element popped.

Types:

Containers can be divided into two groups:

1.     Value based containers

2.     Reference based containers

Value based containers

·         Store copies of objects. If we access an object, the object returns a copy of it. If an external object is changed after it has been inserted in the container it will not affect the content of the container

Reference based containers

·         Store pointers or references to the object. If we access an object, the object returns a reference to it. If an external object is changed after it has been inserted in the container, it affects the content of the container.

Single and Associative

A container may be:

1.     Single value

2.     Associative

Single value containers

·         Each object is stored independently in the container and it is accessed directly or with an iterator.

Associative containers

·         An associative array, map, or dictionary is a container composed of (key,value) pairs, such that each key appears at most once in the container. The key is used to find the value, the object, if it is stored in the container.

 

Examples of container:

Containers are divided in the Standard Template Library into associative containers and standard sequence containers. Besides this two types, so-called container adaptors exist. Data structures that are implemented by containers include arrayslistsmapsqueuessetsstackstablestrees, and vectors.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Unit-04/Lecture-03

 


What is Containership?

 

·         Containership is the ability of a class to contain objects of different classes as member data.

·         Containership is the phenomenon of using one or more classes within the definition of other class.  When a class contains the definition of some other classes, it is referred to as composition, containment or aggregation.  The data member of a new class is an object of some other class.  Thus the other class is said to be composed of other classes and hence referred to as containership. 

·         Composition is often referred to as a “has-a” relationship because the objects of the composite class have objects of the composed class as members.

 

For example,

 

class A could contain an object of class B as a member. Here, all the public methods (or functions) defined in B can be executed within the class A. Class A becomes the container, while class B becomes the contained class. Containership is also referred to as Composition. 

 

Program:

#include<iostream.h>
#include<conio.h>
class base{
public:
void showdata(){cout<<“Base Class OP”<<endl;}
};

class container{
base b;
public:
void showdata(){
cout<<“Container Class OP”<<endl;
b.showdata();
}
};
main(){
clrscr();
container a;
a.showdata();
getch();
return 0;

}

Difference between Inheritance and Containership

 

Inheritance is the ability for a class to inherit properties and behavior from a parent class by extending it, while Containership is the ability of a class to contain objects of different classes as member data. If a class is extended, it inherits all the public and protected properties/behavior and those behaviors may be overridden by the subclass.

But if a class is contained in another, the container does not get the ability to change or add behavior to the contained.

 

·         Inheritance represents an “is-a” relationship in OOP, while Containership represents a “has-a” relationship.

 

 

 

 

 

 

S.NO

RGPV QUESTIONS

Year

Marks

Q.1

What is container class? How it is different from inheritance.

June 2010

8

Q.2

Explain different type of container?

June 2014

3

 

 

 

 

 

 

Unit-04/Lecture-04

 

 

Iterator

·         An iterator is an object that enables a programmer to traverse a container, particularly lists. An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range using a set of operators (with at least the increment (++) and dereference (*) operators.

·         The most obvious form of iterator is a pointer: A pointer can point to elements in an array, and can iterate through them using the increment operator (++).

 

Iterator Classes

Iterators are divided into classes. These are not real C++ classes, but simply categories of kind of iterators. Each category specifies the operations the iterator supports. For example, some iterators support incrementing but not decrementing, some support dereferencing for getting data but not for storing data, some support scalar arithmetic, i.e., adding n, and some don't. 

 

Varieties of Iterators

Iterator form

Description

input iterator

Read only, forward moving

output iterator

Write only, forward moving

forward iterator

Both read and write, forward moving

bidirectional iterator

Read and write, forward and backward moving

random access iterator

Read and write, random access

 

 

 

Input iterator

InputIterator is a useful but limited class of iterators.  If iter is an InputIterator,

·         ++iter and iter++ to increment it, i.e., advance the pointer to the next element

·         *iter to dereference it, i.e., get the element pointed to

·         == and != to compare it another iterator.

This is called an input iterator because you can only use it to "read" data from a container.

Output iterator

OutputIterator is another limited class of iterators, basically the opposite of InputIterator. If iter is an OutputIterator,

·         ++iter and iter++ to increment it, i.e., advance the pointer to the next element

·         *iter = ... to store data in the location pointed to

·         Output iterators are only for storing.

 

Forward iterator

ForwardIterator combines InputIterator and OutputIterator. They also support:

·         saving and reusing.

Bidirectional iterator.

If iter is a BidirectionalIterator:

·         all ForwardIterator operations

·         --iter and iter-- to decrement it, i.e., advance the pointer to the previous element

Random access iterator.

If iter1 and iter2 are RandomAccessIterator's,

·         all BidirectionalIterator operations

·         standard pointer arithmetic, i.e., iter + n, iter - n, iter += n, iter -= n, and iter1 - iter2 (but not iter1 + iter2)

·         all comparisons, i.e., iter1 > iter2, iter1 < iter2, iter1 >= iter2, and iter1 <= iter2

 

Unit-04/Lecture-05

 

 

Heterogeneous containers

·         C++ Containers are designed to hold objects of a single type using templates. If you want different types that are all derived from one type you can store a container of pointers 

·         A heterogeneous container is a container that can store elements of different types. For strongly typed languages like C++, such kind of container isn't a natural or built-in feature. Many solutions exist though, to simulate this heterogeneous property, but they often involve memory space or runtime speed trade-offs.

 

Solutions to implement a heterogeneous container, and their main drawbacks.

1.       Classical Polymorphism

In the classical polymorphism solution, the container holds pointers to a base class from which several classes are derived. The heterogeneous property is then achieved through the dynamic type of each element of the collection.

Limitations:

·         Virtual functions can't be inlined in this case

·         Impossibility to directly use built-in types

·         Loss of type identity and traits specific to the derived classes

   2. Union-like Elements

A container of unions simulates a heterogeneous behavior, since the value of a union can be interpreted through multiple types. However, mere unions have severe limitations:

·         They only accept a restricted set of types

·         They aren't type-safe

·         They must reserve a space at least equivalent to the size of the largest type of the union, resulting in a waste of memory space in a heterogeneous container

   3.Tuple

A tuple is a finite collection of elements. In C++, the implementation of a tuple is a fixed-size container that can hold elements of any type. In such an implementation, element access is resolved statically resulting in no runtime overhead.

Limitations:

·         Fixed size

·         No dynamic access to elements

 

 

Persistent Object

·         A persistent object can live after the program which created it has stopped. Persistent objects can even outlive different versions of the creating program, can outlive the disk system, the operating system, or even the hardware on which the OS was running when they were created.

·         Persistence is the ability of an object to survive the lifetime of the OS process in which it resides.

 

·         Objects created may have different lifetimes:

          Transient: allocated memory managed by the programming language run-time system.

   E.g., local variables in procedures have a lifetime of a procedure execution

            global variables have a lifetime of a program execution

  

Persistent: allocated memory and stored managed by ODBMS runtime system.

 

·         Classes are declared to be persistence-capable or transient.

·         Different languages have different mechanisms to make objects persistent:

 

        Creation time: Object declared persistent at creation time (e.g., in C++ binding) (class must be persistent-capable)

        Persistence by reachability: object is persistent if it can be reached from a persistent object (e.g., in Java binding) (class must be persistent-capable).

 

There are two types of persistent objects:

  • standalone instance is stored in a database table row, and has a unique object identifier. Standalone objects may also be referred to as referenceable objects.
  • An embedded instance is not stored in a database table row, but rather is embedded within another structure. Embedded objects may also be referred to as nonreferenceable objects or value instances.

 

How to achieve persistence?

 

·         Should be transparent to application developer.

·         Storing object state on persistent storage before de-activation.

·         Upon activation, load object state from persistent storage.

 

 

Persistence Object Store

 

A persistent object store is a computer storage system that records and retrieves complete objects, or provides the illusion of doing so.

 

In order to store an object to be persistent, it must be stored on some disk in same form.but there is a  problem associated with the formats, because objects have two aspects:

·         The data associated with attributes

·         The processes associated with method.

There are 2 ways for the implementation of persistent object

·         Storing object in traditional file

·         Use an object oriented database.

 

 

 

 

 

 

 

 

 

Unit-04/Lecture-06

 

 

Streams:

     C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. In input operations, data bytes flow from an input source .  into the program. In output operations, data bytes flow from the program to an output sink.

 

Streams acts as an intermediaries between the programs and the actual IO devices, in such the way that frees the programmers from handling the actual devices, so as to archive device independent IO operations.

 

• An input stream is a flow of characters into the program.

• An output stream is a flow of characters out of the program.

• cin is a predefined input stream (defined in <iostream>).

cout is a predefined output stream (defined in <iostream>).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

IOstreams.png

 

 

 

The iostream library is an object-oriented library that provides input and output functionality using streams.

A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can basically be represented as a source or destination of characters of indefinite length.

 

C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO, bytes are grouped and converted to types such as int, double, string or user-defined types. In unformatted or low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO operations are supported via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a consistent public IO interface.

 

Headers

IO  is provided in  headers  <iostream>  (which  included <ios>,  <istream>,  <ostream>  and  <streambuf>),  <fstream>  (for file IO) , and  <sstream>  (for string IO).

 

 

click on an element for detailed information

 

 

 

 

 

Header File

Function and Description

<iostream>

This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.

<iomanip>

This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.

<fstream>

This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.

 

 

Concept of file

 

Files are the most important mechanism for storing data permanently on mass-storage devices. Permanently means that the data is not lost when the machine is switched off. Files can contain:

• Data in a format that can be interpreted by programs, but not easily by humans (binary files);

• Alphanumeric characters, codified in a standard way.

 

Operations on files

·         Opening.

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

 

·         Closing

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

 

S.NO

RGPV QUESTIONS

Year

Marks

Q.1

What are stream? What are the stream used for inputting and outputting?

June 2010

10

Q.2

How file can be open and close explicitly in a program?

June 2014

7

Q.3

Write short note on persistent object?

June 2014

2

 

 

 

 

 

 

 

 

 

 

Unit-04/Lecture-07

 

 

Object oriented programming language

 

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods

 

FEATURES OF OOP:

1.                   Object

2.                   Class

3.                   Data Hiding and Encapsulation

4.                   Dynamic Binding

5.                   Message Passing

6.                   Inheritance

7.                   Polymorphism

 Benefits of OOP

·         The procedural-oriented languages focus on procedures, with function as the basic unit. You need to first figure out all the functions and then think about how to represent data.

·         The object-oriented languages focus on components that the user perceives, with objects as the basic unit.

Object-Oriented technology has many benefits:

 

·         Ease in software design

·         Ease in software maintenance

·         Reusable software:

 

Procedural oriented programming (pop):-

A program in a procedural language is a list of instruction where each statement tells the computer to do something. It focuses on procedure (function) & algorithm is needed to perform the derived computation.

When program become larger, it is divided into function & each function has clearly defined purpose. Dividing the program into functions & module is one of the cornerstones of structured programming.

E.g.:- c, basic, FORTRAN.

Characteristics of Procedural oriented programming:-

  • It focuses on process rather than data.
  • It takes a problem as a sequence of things to be done such as reading, calculating and printing. Hence, a number of functions are written to solve a problem.
  • A program is divided into a number of functions and each function has clearly defined purpose.
  • Most of the functions share global data.
  • Data moves openly around the system from function to function.

Drawback of Procedural oriented programming (structured programming):-

  • It emphasis on doing things. Data is given a second class status even through data is the reason for the existence of the program.
  • Since every function has complete access to the global variables, the new programmer can corrupt the data accidentally by creating function. Similarly, if new data is to be added, all the function needed to be modified to access the data.
  • It is often difficult to design because the components function and data structure do not model the real world.

Object oriented programming :

The main idea behind object oriented approach is to combine process (function) and data into a unit called an object. Hence, it focuses on objects rather than procedure.

Characteristics of Object Oriented Programming :

  • Objects:-

Any physical or logical units having specific characteristics which match to the real word are called as object.

Object oriented approach views a problem in terms of objects rather than procedure for doing it.

Objects can be classified below:-

  • Physical objects
  • Elements of the computer user environment
  • Collection of data
  • User defined data types
  • Components in computer games

Features / advantages of Object Oriented Programming :-

  1. It emphasis in own data rather than procedure.
  2. It is based on the principles of inheritance, polymorphism, encapsulation and data abstraction.
  3. It implements programs using the objects.
  4. Data and the functions are wrapped into a single unit called class so that data is hidden and is safe from accidental alternation.
  5. Objects communicate with each other through functions.
  6. New data and functions can be easily added whenever necessary.

 

S.NO

RGPV QUESTIONS

Year

Marks

Q.1

Write a short note on object oriented programming language

Dec 2003

 

5

Q.2

Compare object oriented and procedure oriented programming language

Dec 2005

6

 

 

 

 

 

Back To Home