Вы находитесь на странице: 1из 17

Smt.

Chandaben Mohanbhai Patel Institute of Computer


Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

Unit-I Foundation of C++


 C++ is a statically typed, compiled, general-purpose, case-sensitive, free-
form programming language that supports procedural, object-oriented, and
generic programming.
 C++ is regarded as a middle-level language, as it comprises a combination
of both high-level and low-level language features.
 C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in
Murray Hill, New Jersey, as an enhancement to the C language and
originally named ‘C with Classes’ but later it was renamed C++ in 1983.

Usage of C++
 By the help of C++ programming language, we can develop different types
of secured and robust applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware
Features of C++
1. Simple
 C++ is a simple language in the sense that it provides structured
approach (to break the problem into parts), rich set of library
functions, data types etc.
2. Machine Independent or Portable
 Unlike assembly language, c programs can be executed in many
machines with little bit or no change. But it is not platform-
independent.
3. Mid-level programming language
 C++ is also used to do low level programming. It is used to develop
system applications such as kernel, driver etc. It also supports the
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

feature of high level language. That is why it is known as mid-level


language.
 Structured programming languageC++ is a structured
programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify.
4. Rich Library
 C++ provides a lot of inbuilt functions that makes the development
fast.
5. Object Oriented
 C++ is object oriented programming language. OOPs makes
development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as
project size grows.
6. Compiler based
 C++ is a compiler based programming language, it means without
compilation no C++ program can be executed. First we need to
compile our program using compiler and then we can execute our
program

Structure of C++ Program

programs are a sequence of instructions or statements. These statements form the


structure of a C++ program. C++ program structure is divided into various
sections, namely, headers, class definition, member functions
definitions and main function.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

 Note that C++ provides the flexibility of writing a program with or without
a class and its member functions definitions. A simple C++ program
(without a class) includes comments, headers, namespace, main() and
input/output statements.
 Comments are a vital element of a program that is used to increase the
readability of a program and to describe its functioning. Comments are not
executable statements and hence, do not increase the size of a file.


C++ supports two comment styles: single line comment and multiline
comment. Single line comments are used to define line-by-line descriptions.
Double slash (//) is used to represent single line comments. To understand the
concept of single line comment, consider this statement.
/ An example to demonstrate single line comment It can also be written
as
/ / An example to demonstrate
/ / single line comment

Multiline comments are used to define multiple lines descriptions and are
represented as / * * /. For example, consider this statement.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

/* An example to demonstrate
multiline comment */
Generally, multiline comments are not used in C++ as they require more space
on the line. However, they are useful within the program statements where
single line comments cannot be used. For example, consider this statement.

for(int i = 0; i<10; //loop runs 10 times i++)

Compiler ignores everything written after the single line comment and hence,
an error occurs. Therefore, in this case multiline comments are used. For
example, consider this statement.

for(int i = 0; i<10; /*loop runs 10 times */ i++)


Headers: Generally, a program includes various programming elements like
built-in functions, classes, keywords, constants, operators, etc., that are
already defined in the standard C++ library.
In order to use such pre-defined elements in a program, an appropriate header
must be included in the program. The standard headers contain
the information like prototype, definition and return type of library
functions, data type of constants, etc.
As a result, programmers do not need to explicitly declare (or define) the
predefined programming elements.
Standard headers are specified in a program through the preprocessor
directive" #include. In Figure, the iostream header is used. When the compiler
processes the instruction #inc1ude<iostream>,
it includes the contents of iostream in the program. This enables the
programmer to use standard input, output and error facilities that are
provided only through the standard streams defined in <iostream>.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

These standard streams process data as a stream of characters, that is, data is
read and displayed in a continuous flow. The standard streams defined in
<iostream> are listed here.
cin (pronounced "see in") : It is the standard input stream that is associated
with the standard input device (keyboard) and is used to take the input from
users.
• cout (pronounced "see out") : It is the standard output stream that is
associated with the standard output device(monitor) and is used to display the
output to users.
• cerr (pronounced "see err") : It is the standard error stream that is
associated with the standard error device (monitor) and is used to report errors
to the users. The cerr object does not have a buffer (temporary storage area)
and hence, immediately reports errors to users. '
• clog (pronounced "see log"): It is the buffered error stream that is associated
with the standard error device (computer screen) and is used to report errors
to users. Unlike cerr, clog reports errors to users only when the buffer is full
Namespace:
Since its creation, C++ has gone through many changes by the C++ Standards
Committee. One of the new features added to this language is namespace. A
namespace permits grouping of various entities like classes, objects, functions
and various C++ tokens, etc., under a single name.
Different users can create separate namespaces and thus can use similar names
of the entities. This avoids compile-time error that may exist due to identical-
name conflicts.
The C++ Standards Committee has rearranged the entities of the standard
library under a namespace called std. In Figure, the statement using namespace
std informs the compiler to include all the entities present in the namespace
std. The entities of a namespace can be accessed in different ways which are
listed here.
• By specifying the using directive
using namespace std;
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

cout<<"Hello World";
• By specifying the full member name
std: :cout<<"Hello World";
• By specifying the using declaration
using std:: cout;
cout<<"Hello World";
As soon as the new-style header is included, its contents are included in the
std namespace. Thus, all the modern C++ compilers support these statements.
#include<iostream>
using namespace std;
However, some old compilers may not support these statements. In that case,
the statements are replaced by this single statement.
#include<iostream.h>
Extension of C++ file is .cpp .
C++ is designed to be a compiled language. It is generally translated into
machine language that can be understood directly by the system.
Most frequently used and free available compiler is GNU C/C++ compiler.
After compilation, compiler will generate a.out executable file that will show
the output of program.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

C vs C++

1) C follows the procedural style C++ is multi-paradigm. It supports both procedural


programming. and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class members to
make it inaccessible for outside users.

3) C follows the top-down C++ follows the bottom-up approach.


approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in structure.
structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin and cout to perform
mainly used for input/output. input and output operations.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided into functions and classes.
into procedures and modules

10) C does not provide the feature C++ supports the feature of namespace.
of namespace.

11) Exception handling is not easy C++ provides exception handling using Try and
in C. It has to perform using Catch block.
other functions.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

 C++ I/O operation is using the stream concept. Stream is the sequence of
bytes or flow of data. It makes the performance fast.
 If bytes flow from main memory to device like printer, display screen, or a
network connection, etc., this is called as output operation.
 If bytes flow from device like printer, display screen, or a network
connection, etc to main memory, this is called as input operation.
I/O Library Header Files

Header File Function and Description

<iostream> It is used to define the standard output stream, standard input


stream and standard error stream.

<fstream> It is used to declare services for user-controlled file processing.

 The cout is a predefined object of ostream class.


 It is connected with the standard output device, which is usually a
display screen.
 The cout is used in conjunction with stream insertion operator (<<) to
display the output on a console.
 Example:

 Standard input stream (cin) The cin is a predefined object of istream class.
 It is connected with the standard input device, which is usually a
keyboard.
 The cin is used in conjunction with stream extraction operator (>>) to
read the input from a console.
 The endl is a predefined object of ostream class.
 It is used to insert a new line characters and flushes the stream.
 Standard end line (endl) The endl is a predefined object of ostream class.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

 It is used to insert a new line characters and flushes the stream.

Data Type in C++


 A data type specifies the type of data that a variable can store such as
integer, floating, character etc.
 Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

C++ Variable
 A variable is a name of memory location. It is used to store data.
 Its value can be changed and it can be reused many times.
 It is a way to represent memory location through symbol so that it can
be easily identified.
 Example:
• int x;
• float y;
• char z;
• int x=5,b=10; //declaring 2 variable of integer type
Rules for defining variables
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

 A variable can have alphabets, digits and underscore.


 A variable name can start with alphabet and underscore only. It can't start
with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float
etc.
 Variable Scope in C++
 Local Variables
• Variables that are declared inside a function or block are local
variables. They can be used only by statements that are inside that
function or block of code.
• Local variables are not known to functions outside their own.
 Global Variables
 Global variables are defined outside of all the functions, usually on
top of the program. The global variables will hold their value
throughout the life-time of your program.
 A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its
declaration.
Constants
Constants refer to fixed values that the program may not alter and they are
called literals.
 Constants can be of any of the basic data types and can be divided into
Integer Numerals, Floating-Point Numerals, Characters, Strings and
Boolean Values.
 There are two simple ways in C++ to define constants −
 Using #define preprocessor.
 Using const keyword.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

Array in C++

 How to declare an array in C++?


dataType arrayName[arraySize];

for eg. float marks[5];


 Elements of an Array and How to access them?
o You can access elements of an array by using indices.
o Suppose you declared an array mark as above.
o The first element is mark[0], second element is mark[1] and so on.

o
 Some Points to be Remembered.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

o Arrays have 0 as the first index not 1. In this example, mark[0] is the first
element.
o If the size of an array is n, to access the last element, (n-1) index is used.
In this example, mark[4] is the last element.
o Suppose the starting address of mark[0] is 2120d. Then, the next address,
a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because
the size of float is 4 bytes.

 How to initialize an array in C++ programming?

o int mark[5] = {19, 10, 8, 17, 9};


o int mark[] = {19, 10, 8, 17, 9};
 How to access array element understand through program?

o #include <iostream>
o using namespace std;
o
o int main(){
o int arr[] = {11, 22, 33, 44, 55};
o cout<<arr[0]<<endl;
o cout<<arr[1]<<endl;
o cout<<arr[2]<<endl;
o cout<<arr[3]<<endl;
o cout<<arr[4]<<endl;
o return 0;
o }
1-D array
int arr[10];

Initialization of 1-D Array


int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
* C++ One Dimensional Array */

#include<iostream.h>
#include<conio.h>
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

void main()
{
clrscr();
int arr[5] = {1, 2, 3, 4, 5};
int i;
for(i=0; i<5; i++)
{
cout<<"arr["<<i<<"] = "<<arr[i]<<"\n";
}
getch();
}
Inline Function

 Inline function is one of the important feature of C++.


 When the program executes the function call instruction the CPU stores the
memory address of the instruction following the function call,
 copies the arguments of the function on the stack and finally transfers
control to the specified function.
 The CPU then executes the function code, stores the function return value
in a predefined memory location/register and returns control to the calling
function.
 This can become overhead if the execution time of function is less than
the switching time from the caller function to called function (callee). For
functions that are large and/or perform complex tasks, the overhead of the
function call is usually insignificant compared to the amount of time the
function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code. This overhead occurs for
small functions because execution time of small function is less than the
switching time.
 C++ provides an inline functions to reduce the function call overhead.
 Inline function is a function that is expanded in line when it is called.
 When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

 This substitution is performed by the C++ compiler at compile time. Inline


function may increase efficiency if it is small.
 The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
 Remember, inlining is only a request to the compiler, not a command.
Compiler can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement
doesn’t exist in function body.
5) If a function contains switch or goto statement.\
 For Example
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //Output: The cube of 3 is: 27

Bad programming Style


class S
{
public:
inline int square(int s) // redundant use of inline
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

{
// this function is automatically inline
// function body
}
};
Good Programming style
class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{

Default Argument in C++


 The default arguments are used when you provide no arguments or
only few arguments while calling a function.
 The default arguments are used during compilation of program.
 For example, lets say you have a user-defined function sum declared
 int sum(int a=10, int b=20)
 now while calling this function you do not provide any arguments,
simply called sum();
 then in this case the result would be 30, compiler used the default
values 10 and 20 declared in function signature.
 If you pass only one argument like this: sum(80) then the result
would be 100,
 using the passed argument 80 as first value and 20 taken from the
default argument.

Rules of default arguments


If you assign default value to an argument, the subsequent arguments must have
default values assigned to them, else you will get compilation error.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

Valid use of Default Argument


int sum(int a=10, int b=20, int c=30);
int sum(int a, int b=20, int c=30);
int sum(int a, int b, int c=30);

Invalid use of Default Argument


int sum(int a=10, int b, int c=30);
int sum(int a, int b=20, int c);
int sum(int a=10, int b=20, int c);

Function Overloading
Function overloading is a feature in C++ where two or more functions can have
the same name but different parameters.

Function refers to a segment that groups code to perform a specific task.


In C++ programming, two functions can have same name if number and/or type
of arguments passed are different.
Smt. Chandaben Mohanbhai Patel Institute of Computer
Applications - Changa
B.Sc.(IT) SEMESTER – III (Academic year 2019-20)
CA 503 Object Oriented Programming.

These functions having different number or type (or both) of parameters are
known as overloaded functions. For example:

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Here, all 4 functions are overloaded functions because argument(s) passed to


these functions are different.

Notice that, the return type of all these 4 functions are not same. Overloaded
functions may or may not have different return type but it should have different
argument(s).

// Error code

int test(int a) { }

double test(int b){ }

The number and type of arguments passed to these two functions are same even
though the return type is different. Hence, the compiler will throw error.
****************************************************************