Vous êtes sur la page 1sur 14

UNIT-I:

Objectives: Exposure to basics of object oriented mode, C++ programming and I/O
in C++
INTRODUCTION: Differences between C and C++, the Object Oriented Technology,
Disadvantage of
Conventional Programming, Concepts of Object Oriented Programming, Advantages
of OOP, Structure
of a C++ Program, Header Files and Libraries.
INPUTAND OUTPUT IN C++: Introduction, Streams In C++ and Stream Classes,
Pre-Defined Streams, Stream Classes, 'Formatted and Unformatted Data,
Unformatted Console I/O Operations, Member Functions of istream Class, Formatted
Console I/O Operations, Bit Fields, Flags without Bit Field, Manipulators, User
Defined Manipulators.
Following are the differences Between C and C++ :
C

C++

1. C is Procedural Language.

1. C++ is non Procedural i.e Object


oriented Language.

2. No virtual Functions are present in C

2. The concept of virtual Functions


are used in C++.

3. In C, Polymorphism is not possible.

3. The concept of polymorphism is


used in C++.
Polymorphism is the most Important
Feature of OOPS.

4. Operator overloading is not possible in C.

4. Operator overloading is one of


the greatest Feature of C++.

5. Top down approach is used in Program


Design.

5. Bottom up approach adopted in


Program Design.

6. No namespace Feature is present in C


Language.

6. Namespace Feature is present in


C++ for avoiding Name collision.

7. Multiple declaration of global variables are 7. Multiple declaration of global


allowed.
variables are not allowed.
8. In C

8. In C++

scanf() Function used for Input.

printf() Function used for output.

9. Mapping between Data and Function is


difficult and complicated.

Cin>> Function used for


Input.

Cout<< Function used for


output.

9. Mapping between Data and


Function can be used using
"Objects"

10. In C, we can call main() Function through 10. In C++, we cannot call main()
other Functions
Function through other functions.
11. C++ allows the declaration of
11. C requires all the variables to be defined
variable anywhere in the scope i.e at
at the starting of a scope.
time of its First use.
12. No inheritance is possible in C.

12. Inheritance is possible in C++

13. In C, malloc() and calloc() Functions are


used for Memory Allocation and free()
function for memory Deallocating.

13.In C++, new and delete


operators are used for Memory
Allocating and Deallocating.

14. It supports built-in and primitive data


types.

14. It support both built-in and user


define data types.

15. In C, Exception Handling is not present.

15. In C++, Exception Handling is


done with Try and Catch block.

Features of
OOPs
The prime
purpose of
C++

programming was to add object orientation to the C programming language, which


is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object, in code,
that has certain properties and methods. While designing C++ modules, we try to
see whole world in the form of objects. For example a car is an object which has
certain properties such as color, number of doors, and the like. It also has certain
methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming:
Object
This is the basic unit of object oriented programming. That is both data and function
that operate on data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually
define any data, but it does define what the class name means, that is, what an
object of the class will consist of and what operations can be performed on such an
object.
Abstraction

Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in
program without presenting the details.
For example, a database system hides certain details of how data is stored and
created and maintained. Similar way, C++ classes provides different methods to the
outside world without giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the
same place. While working with procedural languages, it is not always clear which
functions work on which variables but object-oriented programming provides you
framework to place the data and the relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability.
As the name suggests Inheritance is the process of forming a new class from an
existing class that is from the existing class called as base class, new class is
formed called as derived class.
This is a very important concept of object-oriented programming since this feature
helps to reduce the code size.
ypes of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is
the most simplest form of Inheritance.

Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than
two base classes.

Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.

Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn
inherits from some other class. The Super class for one, is sub class for the other.

Hybrid (Virtual) Inheritance


Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Polymorphism
The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called polymorphism.
Poly refers to many. That is a single function or an operator functioning in many
ways different upon the usage is called polymorphism.
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting
operator or function is made to operate on new data type, it is said to be
overloaded.
Advantages of OOPs

OOP provides a clear modular structure for programs.


It is good for defining abstract data types.
Implementation details are hidden from other modules and other modules
has a clearly defined interface.

It is easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
objects, methods, instance, message passing, inheritance are some
important properties provided by these particular languages
encapsulation, polymorphism, abstraction are also counts in these
fundamentals of programming language.
It implements real life scenario.
In OOP, programmer not only defines data types but also deals with
operations applied for data structures.

Structure of C++ Program : Layout of C++ Program


C++ Programming language is most popular language after C Programming
language. C++ is first Object oriented programming language.We have summarize
structure of C++ Program in the following Picture

Structure of C++ Program


1 : Header File Declaration Section
1. Header files used in the program are listed here.
2. Header File provides Prototype declaration for different library functions.
3. We can also include user define header file.
4. Basically all preprocessor directives are written in this section.
2 : Global Declaration Section
1. Global Variables are declared here.
2. Global Declaration may include
o Declaring Structure
o Declaring Class
o Declaring Variable
3 : Class Declaration Section
1. Actually this section can be considered as sub section for the global
declaration section.
2. Class declaration and all methods of that class are defined here.
4 : Main Function
1. Each and every C++ program always starts with main function.

2. This is entry point for all the function. Each and every method is called
indirectly through main.
3. We can create class objects in the main.
4. Operating system call this function automatically.
Header Files and Libraries.
cassert (assert.h)
This library contains only the function assert. You use
assert(assertion);
to test the validity of an assertion. If assertion is false, assert writes an error
message and terminates program execution. You can disable all occurrences
of assert in your program by placing the directive
#define NDEBUG
before the include directive.
cctype (ctype.h)
Most functions in this library classify a given ASCII character as a letter, a digit, and
so on. Two other functions convert letters between uppercase and lowercase.
The classification functions return a true value if ch belongs to the specified group;
otherwise they return false.
isalnum(
Returns true if ch is either a letter or a decimal digit
ch)
isalpha(
Returns true if ch is a letter
ch)
iscntrl(c
Returns true if ch is a control character (ASCII 127 or 0 to 31)
h)
isdigit(c
Returns true if ch is a decimal digit
h)
isgraph(
Returns true if ch is printable and nonblank
ch)
islower(
Returns true if ch is a lowercase letter
ch)
isprint(c
Returns true if ch is printable (including blank)
h)
ispunct(
Returns true if ch is a punctuation character
ch)
isspace( Returns true if ch is a whitespace character: space, tab, carriage return,
ch)
new line, or form feed
isupper(
Returns true if ch is an uppercase letter
ch)
isxdigit(
Returns true if ch is a hexidecimal digit
ch)
toascii(c
Returns ASCII code for ch
h)
tolower( Returns the lowercase version of ch if ch is an uppercase letter; otherwise
ch)
returns ch
toupper( Returns the uppercase version of ch if ch is a lowercase letter; otherwise
ch)
returns ch

cfloat (float.h)
Defines named constants that specify the range of floating-point values.
climits (limits.h)
Defines named constants that specify the range of integer values.
cmath (math.h)
The C++ functions in this library compute certain standard mathematical functions.
These functions are overloaded to accomodatefloat, double, and long double.
Unless otherwise indicated, each function has one argument, with the return type
being the same as the argument type (either float, double, or long double).
acos Returns the arc cosine
asin Returns the arc sine
atan Returns the arc tangent
atan
Returns the arc tangent x/y for arguments x and y
2
ceil Rounds up
cos Returns the cosine
cos
Returns the arc cosine
h
exp Returns ex
fabs Returns the absolute value
floo
Rounds down
r
fmo
Returns x modulo y for arguments x and y
d
frex For arguments x and eptr, where x = m * 2e, returns m and sets eptr to point
p
to e
ldex
Returns x * 2e , for arguments x and e
p
log Returns the natural log
log1
Returns the log base 10
0
mod For arguments x and iptr, returns the fractional part of x and sets iptr to point
f
to the integer part of x
pow Returns xy , for arguments x and y
sin Returns the sine
sinh Returns the hyperbolic sine
sqrt Returns the square root
tan Returns the tangent
tan
Returns the hyperbolic tangent
h
cstdlib (stdlib.h)
abort Terminates program execution abnormally
abs
Returns the absolute value of an integer
atof
Converts a string argument to floating point
atoi
Converts a string argument to an integer
exit
Terminates program execution
rand() Generates an unsigned int between 0 and RAND_MAX, a named constant
defined in cstdlib header file

srand(unsigned n) Seeds the rand() function so that it generates different


sequences of random numbers. srand is often used in conjunction
with the time function from the ctime library. For example,
srand(time(0));
cstring (string.h)
This library enables you to manipulate C strings that end in the char '\0', the null
char. Unless noted otherwise, these functions return a pointer to the resulting string
in addition to modifying an appropriate argument. The argument ch is a character, n
is an integer, and the other arguments are strings, which usually means they are
names of a char array, but can be string constants in some cases. For example,
strcmp("Hello", "Goodbye");
strcat(toS, fromS)
Copies fromS to the end of toS
strncat(toS, fromS, n) Copies at most n characters of fromS to the end
of toS and appends \0
strcmp(str1, str2)
Returns an integer that is negative if str1 < str2,
zero if str1 == str2, and positive if str1 > str2
stricmp(str1, str2)
Behaves like strcmp, but ignores case
strncmp(str1, str2, n) Behaves like strcmp, but compares the first
n characters of each string
strcpy(toS, fromS)
Copies fromS toS
strncpy(toS, fromS, n) Copies n characters of fromS to toS, truncating
or padding with \0 as necessary
strspn(str1, str2)
Returns the number of initial consecutive characters
of str1 that are not in str2
strcspn(str1, str2)
Returns the number of initial consecutive characters
of str1 that are in str2
strlen(str)
Returns the length of str, excluding \0
strlwr(str)
Converts any uppercase letters in str to lowercase
without altering other characters
strupr(str)
Converts any lowercase letters in str to uppercase
without altering other characters
strchr(str, ch)
Returns a pointer to the first occurrence of ch
in str; otherwise returns NULL
strrchr(str, ch)
Returns a pointer to the last occurrence of ch in
str; otherwise returns NULL
strpbrk(str1, str2)
Returns a pointer to the first character in str1
that also appears in str2; otherwise returns NULL
strstr(str1, str2)
Returns a pointer to the first occurrence of str2
in str1; otherwise returns NULL
strtok(str1, str2)
Finds the next token in str1 that is followed by
str2, returns a pointer to the token and writes
NULL immediately after the token in str1
ctime
Defines functions for manipulating time and dates.
exception
Defines classes, types, and functions that relate to exception handling. A portion of
the class exception is shown below.
class exception
{
public:

exception() throw();
virtual -exception() throw();
exception &operator=(const exception %exc) throw();
virtual const char *what() const throw();
}
fstream (fstream.h)
Declares the C++ classes that support file I/O.
iomanip (iomanip.h)
The manipulation in this library affect the format of steam operations. Note that
iostream contains additional manipulators.
setbase(b)
Setts number base to b = 8, 10, or 16
setfill(f)
Sets fill character to f
setprecision(n) Sets floating-point precision to integer n
setw(n)
Sets field width to integer n
iostream (iostream.h)
The manipulators in this library affect the format of stream operations. Note that
iomanip contains additional manipulators.
dec
Tells subsequent operation to use decimal representation
end1
Inserts new-line character \n and flushes output stream
ends
Inserts null character \0 in an output stream
flush
Flushes an output stream
hex
Tells subsequent I/O operations to use hexadecimal
representation
oct
Tells subsequent I/O operation to use octal representation
ws
Extracts whitespace characters on input stream
string
This library enables you to manipulate C++ strings. Described here is a selection of
the functions that this library provides. In addition, you can use the following
operators with C++ strings: =, +, ==, !=, <, <=, >, >=, <<, and >>. Note that
positions within a string begin at 0.
erase()
Makes the string empty
erase(pos, len)
Removes the substring that begins at position pos and
contains len characters
find(subString)
Returns the position of a substring within the string
length()
Returns the number of characters in the string
(same as size)
replace(pos, len, str) Replaces the substring that begins at position
pos and contains len characters with the string str
size()
Returns the number of characters in ths string
(same as length)
substr(pos, len)
Returns the substring that begins at position pos
and contains len characters
INPUTAND OUTPUT IN C++: Introduction, Streams In C++ and Stream Classes,
Pre-Defined Streams, Stream Classes, Formatted and Unformatted Data,
Unformatted Console I/O Operations, Member Functions of istream Class, Formatted
Console I/O Operations, Bit Fields, Flags without Bit Field, Manipulators, User
Defined Manipulators.

Input and output (I/O) streams


Input and output functionality is not defined as part of the core C++ language, but
rather is provided through the C++ standard library (and thus resides in the std
namespace). In previous lessons, you included the iostream library header and
made use of the cin and cout objects to do simple I/O. In this lesson, well take a
look at the iostream library in more detail.
The iostream library
When you include the iostream header, you gain access to a whole heirarchy of
classes responsible for providing I/O functionality (including one class that is
actually named iostream). The class heirarchy for the non-file-I/O classes looks like
this:

The first thing you may notice about this hierarchy is that it uses multiple
inheritance (that thing we told you to avoid if at all possible). However, the iostream
library has been designed and extensively tested in order to avoid any of the typical
multiple inheritance problems, so you can use it freely without worrying.
Streams
The I/O in C++ is implemented with streams. Abstractly, a stream can be
thought of as a sequence of bytes of infinite length that is used as a buffer
to hold data that is waiting to be processed.
Typically we deal with two different types of streams. Input streams are used to hold
input from a data producer, such as a keyboard, a file, or a network. For example,
the user may press a key on the keyboard while the program is currently not
expecting any input. Rather than ignore the users keypress, the data is put into an
input stream, where it will wait until the program is ready for it.
Conversely, output streams are used to hold output for a particular data consumer,
such as a monitor, a file, or a printer. When writing data to an output device, the
device may not be ready to accept that data yet -- for example, the printer may still
be warming up when the program writes data to its output stream. The data will sit
in the output stream until the printer begins consuming it.
Some devices, such as files and networks, are capable of being both input and
output sources.

Input/output in C++
Although the ios class is generally derived from ios_base, ios is typically the most
base class you will be working directly with. The ios class defines a bunch of stuff
that is common to both input and output streams. Well deal with this stuff in a
future lesson.
The istream class is the primary class used when dealing with input streams. With
input streams, the extraction operator (>>) is used to remove values from the
stream. This makes sense: when the user presses a key on the keyboard, the key
code is placed in an input stream. Your program then extracts the value from the
stream so it can be used.
The ostream class is the primary class used when dealing with output streams.
With output streams, the insertion operator (<<) is used to put values in the
stream. This also makes sense: you insert your values into the stream, and the data
consumer (eg. monitor) uses them.
The iostream class can handle both input and output, allowing bidirectional I/O.
Finally, there are a bunch of classes that end in _withassign. These stream classes
are derived from istream, ostream, and iostream (respectively) with an assignment
operator defined, allowing you to assign one stream to another. In most cases, you
wont be dealing with these classes directly.
Standard streams in C++
A standard stream is a pre-connected stream provided to a computer program by
its environment. C++ comes with four predefined standard stream objects that
have already been set up for your use. The first two, you have seen before:
1. cin -- an istream_withassign class tied to the standard input (typically the
keyboard)
2. cout -- an ostream_withassign class tied to the standard output (typically the
monitor)
3. cerr -- an ostream_withassign class tied to the standard error (typically the
monitor), providing unbuffered output
4. clog -- an ostream_withassign class tied to the standard error (typically the
monitor), providing buffered output
Unbuffered output is typically handled immediately, whereas buffered output is
typically stored and written out as a block. Because clog isnt used very often, it is
often omitted from the list of standard streams.
A basic example
Heres an example of input and output using the standard streams:
#include <iostream>
int main()
{
using namespace std;
// First we'll use the insertion operator on cout to print
text to the monitor
cout << "Enter your age: " << endl;

// Then we'll use the extraction operator on cin to get


input from the user
int nAge;
cin >> nAge;
if (nAge <= 0)
{
// In this case we'll use the insertion operatior on cerr
to print an error message
cerr << "Oops, you entered an invalid age!" << endl;
exit(1);
}
// Otherwise we'll use insertion again on cout to print a
result
cout << "You entered " << nAge << " years old" <<
endl;
return 0;
}

Pre-Defined Streams

iostream Library
In C Formatted I/O you have learned the formatted I/O in C by calling various
standard functions. In this Module we will discuss how this formatted I/O

implemented in C++ by using member functions and stream manipulators.


If you have completed this C++ Data Encapsulation until C++ Polymorphism,
you should be familiar with class object. In C++ we will deal a lot with
classes. It is readily available for us to use.
We will only discuss the formatted I/O here, for file I/O and some of the
member functions mentioned in this Module, will be presented in another
Module. The discussion here will be straight to the point because some of
the terms used in this Module have been discussed extensively in C
Formatted I/O.
The header files used for formatted I/O in C++ are:
Brief description
Provide basic information required for all stream I/O operation such as cin, cout, cerr and clog
standard input stream, standard output stream, and standard unbuffered and buffered error streams resp
Contains information useful for performing formatted I/O with parameterized stream manipulation.
Contains information for user controlled file processing operations.
Contains information for performing in-memory formatting or in-core formatting. This resembles file proc
but the I/O operation is performed to and from character arrays rather than files.
Contains information for program that mixes the C and C++ styles of I/O.

library

The compilers that fully comply with the C++ standard that use the template
based header files wont need the .h extension. Please refer
to Namespaces for more information.
The iostream class hierarchy is shown below. From the base class ios, we
have a derived class:
Class
Brief description
istream
Class for stream input operation.
ostream
Class for stream output operation.
ios derived classes
So, iostream support both stream input and output. The class hierarchy is
shown below.

Vous aimerez peut-être aussi