Classes and Objects Introduction to Procedural … examples, Mango, Apple and orange members of...

47
1 | Page Classes and Objects Introduction to Procedural Programming In the procedure oriented approach, the problem is considered as the sequence of things to be done such as reading, calculating and printing examples for procedure oriented programming technique are COBOL, FORTRAN and C etc. The main primary focus is on functions. A structure for procedural programming is shown in figure given below. The technique of hierarchical decomposition has been used to mention the tasks to be completed for solving a problem. Typical structure of procedural oriented programs Procedure oriented programming is a technique of writing a sequence of instructions to be followed by the computer and organizing these instructions into groups known as procedures or functions. Flowcharts are used to organize these functions and represent the flow of control from one Function to another. In this multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in. Another serious drawback with the procedural approach is that we do not model real world problems very well. This is because functions are action-oriented and do not really corresponding to the element of the problem. Some Characteristics exhibited by procedure-oriented programming are: • Emphasis is on doing things (algorithms). • Large programs are divided into smaller programs known as functions. • Most of the functions share global data. • Data move openly around the system from function to function. Main Program Function-3 Function-2 Function-1 Function-5 Function-4

Transcript of Classes and Objects Introduction to Procedural … examples, Mango, Apple and orange members of...

1 | P a g e

Classes and Objects

Introduction to Procedural Programming

In the procedure oriented approach, the problem is considered as the sequence of things to be done such as reading, calculating and printing examples for procedure oriented

programming technique are COBOL, FORTRAN and C etc.

The main primary focus is on functions.

A structure for procedural programming is shown in figure given below.

The technique of hierarchical decomposition has been used to mention the tasks to be

completed for solving a problem.

Typical structure of procedural oriented programs

Procedure oriented programming is a technique of writing a sequence of instructions to be

followed by the computer and organizing these instructions into groups known as procedures or functions.

Flowcharts are used to organize these functions and represent the flow of control from one

Function to another.

In this multi- function program, many important data items are placed as global so that

they may be accessed by all the functions. Each function may have its own local data.

Global data are more vulnerable to an inadvertent change by a function.

In a large program it is very difficult to identify what data is used by which function.

In case we need to revise an external data structure, we also need to revise all functions

that access the data.

This provides an opportunity for bugs to creep in.

Another serious drawback with the procedural approach is that we do not model real

world problems very well. This is because functions are action-oriented and do not really corresponding to the element of the problem.

Some Characteristics exhibited by procedure-oriented programming are:

• Emphasis is on doing things (algorithms). • Large programs are divided into smaller programs known as functions.

• Most of the functions share global data.

• Data move openly around the system from function to function.

Main Program

Function-3

Function-2

Function-1

Function-5

Function-4

2 | P a g e

• Functions transform data from one form to another. • Employs top-down approach in program design.

Object Oriented Programming

The major motivating factor in the invention of object-oriented approach is to remove

some of the flaws encountered in the procedural approach.

OOP treats data as a critical element in the program development and does not allow it to flow freely around the system.

It ties data more closely to the function that operate on it, and protects it from accidental modification from outside function.

OOP allows decomposition of a problem into a number of entities called objects and then builds data and function around these objects.

The organization of data and function in object-oriented programs.

The data of an object can be accessed only by the function associated with that object.

However, function of one object can access the function of other objects.

Organization of data and function in OOP

Some of the features of object oriented programming are:

• Emphasis is on data rather than procedure. • Programs are divided into what are known as objects.

• Data structures are designed such that they characterize the objects.

• Functions that operate on the data of an object are ties together in the data structure.

• Data is hidden and cannot be accessed by external function.

• Objects may communicate with each other through function.

3 | P a g e

• New data and functions can be easily added whenever necessary.

• Follows bottom up approach in program design.

Difference between Procedure and OOP

Procedure oriented Object Oriented

Program is divided into small function Program is divided into small objects

Top down Approaches Bottom up approach

Does not have access specifier Has access specifier

Not easy to add new data Easy to add new data

Not proper data hiding, so less secure Data Hiding so provided more security

Example.

C,VB,FORTRAN,Pascal

Example.

C++,VB.net,java,C#.net

Object-oriented programming is the most recent concept among programming paradigms and still means different things to different people.

Basic Concepts of Object Oriented Programming

It is necessary to understand some of the concepts used extensively in object-oriented programming. These include:

• Objects

• Classes • Data abstraction and encapsulation

• Inheritance • Polymorphism • Dynamic binding

• Message passing Objects

Objects are the basic run time entities in an object-oriented system.

They may represent a person, a place, a bank account, a table of data or any item that

the program has to handle.

They may also represent user-defined data such as vectors, time and lists.

Programming problem is analyzed in term of objects and the nature of communication between them.

Program objects should be chosen such that they match closely with the real-world objects.

Objects take up space in the memory and have an associated address like a record in Pascal, or a structure in c.

When a program is executed, the objects interact by sending messages to one another.

For example, if “customer” and “account” are to object in a program, then the

customer object may send a message to the count object requesting for the bank

4 | P a g e

balance.

Each object contain data, and code to manipulate data. Objects can interact without

having to know details of each other‟s data or code.

It is a sufficient to know the type of message accepted, and the type of response returned by the objects.

Although different author represent them differently, following fig. shows two notations that are popularly used in object-oriented analysis and design.

Classes

We just mentioned that objects contain data, and code to manipulate that data.

The entire set of data and code of an object can be made a user-defined data type with

the help of class.

In fact, objects are variables of the type class.

Once a class has been defined, we can create any number of objects belonging to that class.

Each object is associated with the data of type class with which they are created.

A class is thus a collection of objects similar types.

For examples, Mango, Apple and orange members of class fruit.

Classes are user-defined that types and behave like the built-in types of a programming

language.

The syntax used to create an object is not different then the syntax used to create an

integer object in C. If fruit has been defines as a class, then the statement Fruit Mango;

will create an object mango belonging to the class fruit.

Data Abstraction and Encapsulation

The wrapping up of data and function into a single unit (called class) is known as encapsulation.

Data and encapsulation is the most striking feature of a class.

The data is not accessible to the outside world, and only those functions which are

wrapped in the class can access it.

These functions provide the interface between the object‟s data and the program.

This insulation of the data from direct access by the program is called data hiding or

5 | P a g e

information hiding.

Abstraction refers to the act of representing essential features without including the

background details or explanation.

Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, wait, and cost, and function operate on these attributes.

They encapsulate all the essential properties of the object that are to be created.

The attributes are some time called data members because they hold information.

The functions that operate on these data are sometimes called methods or member

function.

Inheritance

Inheritance is the process by which objects of one class acquired the properties of objects of another classes.

It supports the concept of hierarchical classification. For example, the bird, „robin‟ is a part of class „flying bird‟ which is again a part of the class „bird‟.

The principal behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as illustrated in fig

In OOP, the concept of inheritance provides the idea of reusability.

This means that we can add additional features to an existing class without modifying

it.

This is possible by deriving a new class from the existing one.

The new class will have the combined feature of both the classes.

The real appeal and power of the inheritance mechanism is that it.

Allows the programmer to reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduced any undesirable side-effects

into the rest of classes.

6 | P a g e

Polymorphism

Polymorphism is another important OOP concept.

Polymorphism, a Greek term, means the ability to take more than on form.

An operation may exhibit different behavior is different instances.

The behavior depends upon the types of data used in the operation.

For example, consider the operation of addition. For two numbers, the operation will generate a sum.

If the operands are strings, then the operation would produce a third string by concatenation.

The process of making an operator to exhibit different behaviors in different instances

is known as operator overloading.

Following Fig. illustrates that a single function name can be used to handle different

number and different types of argument.

This is something similar to a particular word having several different meanings

depending upon the context.

Using a single function name to perform different type of task is known as function

overloading.

Polymorphism plays an important role in allowing objects having different internal

structures to share the same external interface.

This means that a general class of operations may be accessed in the same manner even

though specific action associated with each operation may differ.

Polymorphism is extensively used in implementing inheritance.

Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the call.

Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time.

It is associated with polymorphism and inheritance.

A function call associated with a polymorphic reference depends on the dynamic type

7 | P a g e

of that reference.

Consider the procedure “draw” in fig. by inheritance, every object will have this

procedure.

Its algorithm is, however, unique to each object and so the draw procedure will be redefined in each class that defines the object.

At run-time, the code matching the object under current reference will be called.

Message Passing

An object-oriented program consists of a set of objects that communicate with each

other.

The process of programming in an object-oriented language, involves the following

basic steps: o Creating classes that define object and their behavior,

o Creating objects from class definitions, and o Establishing communication among objects.

Objects communicate with one another by sending and receiving information much

the same way as people pass messages to one another.

The concept of message passing makes it easier to talk about building systems that

directly model or simulate their real-world counterparts.

A Message for an object is a request for execution of a procedure, and therefore will

invoke a function (procedure) in the receiving object that generates the desired results.

Message passing involves specifying the name of object, the name of the function

(message) and the information to be sent.

Example: Object has a life cycle.

They can be created and destroyed. Communication with an object is feasible as long as it is alive.

Benefits of OOP

OOP offers several benefits to both the program designer and the user.

Object-Orientation contributes to the solution of many problems associated with the development and quality of software products.

The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost.

The principal advantages are:

Through inheritance, we can eliminate redundant code extend the use of existing

Classes.

We can build programs from the standard working modules that communicate with

one another, rather than having to start writing the code from scratch.

8 | P a g e

This leads to saving of development time and higher productivity.

The principle of data hiding helps the programmer to build secure program that can

not be invaded by code in other parts of a programs.

It is possible to have multiple instances of an object to co-exist without any

interference.

It is possible to map object in the problem domain to those in the program.

It is easy to partition the work in a project based on objects.

The data-centered design approach enables us to capture more detail of a model can

implemental form.

Object-oriented system can be easily upgraded from small to large system.

Message passing techniques for communication between objects makes to interface descriptions with external systems much simpler.

Software complexity can be easily managed.

Object Oriented Language

Object-oriented programming is not the right of any particular languages.

Like structured programming, OOP concepts can be implemented using languages

such as C and Pascal.

However, programming becomes clumsy and may generate confusion when the

programs grow large.

A language that is specially id designed to support the OOP concepts makes it easier to

implement them.

The languages should support several of the OOP concepts to claim that they are

object-oriented.

Depending upon the features they support, they can be classified into the following

two categories: 1. Object-based programming languages, and

2. Object-oriented programming languages.

Object-based programming is the style of programming that primarily supports

encapsulation and object identity. Major feature that are required for object based programming are:

• Data encapsulation • Data hiding and access mechanisms • Automatic initialization and clear-up of objects

• Operator overloading

Languages that support programming with objects are said to the objects-based programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based programming language.

Object-oriented programming language incorporates all of object-based programming

features along with two additional features, namely, inheritance and dynamic binding. Object-oriented programming can therefore be characterized by the following statements: Object-based features + inheritance + dynamic binding

Application of OOP

OOP has become one of the programming buzzwords today.

There appears to be a great deal of excitement and interest among software engineers

in using OOP.

Applications of OOP are beginning to gain importance in many areas.

9 | P a g e

The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as window.

Hundreds of windowing systems have been developed, using the OOP techniques.

Real-business system are often much more complex and contain many more objects

with complicated attributes and method.

OOP is useful in these types of application because it can simplify a complex problem.

The promising areas of application of OOP include: • Real-time system • Simulation and modeling

• Object-oriented data bases • Hypertext, Hypermedia, and expertext

• AI and expert systems • Neural networks and parallel programming • Decision support and office automation systems

• CIM/CAM/CAD systems Application of C++

C++ is a versatile language for handling very large programs; it is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real life applications systems.

• Since C++ allow us to create hierarchy related objects, we can build special object-oriented libraries which can be used later by many programmers.

• While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get closed to the machine- level details.

• C++ programs are easily maintainable and expandable. When a new feature needs to be

implemented, it is very easy to add to the existing structure of an object. • It is expected that C++ will replace C as a general-purpose language in the near future.

Program feature Like C, the C++ program is a collection of function. The above example contain only one

function main(). As usual execution begins at main(). Every C++ program must have a main(). C++ is a free form language. With a few exception, the compiler ignore carriage

return and white spaces. Like C, the C++ statements terminate with semicolons.

Comments

C++ introduces a new comment symbol // (double slash). Comment start with a double slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and

whatever follows till the end of the line is ignored. Note that there is no closing symbol. The double slash comment is basically a single line comment. Multiline comments can be written as follows:

// This is an example of // C++ program to illustrate

// some of its features The C comment symbols /*,*/ are still valid and are more suitable for multiline comments. The following comment is allowed:

/* This is an example of C++ program to illustrate

some of its features */

Output operator The only statement in program is an output statement. The statement

10 | P a g e

cout<<”C++ is better than C.”; Causes the string in quotation marks to be displayed on the screen. This statement introduces two new C++ features, cout and <<. The identifier cout(pronounced as C out) is a predefined

object that represents the standard output stream in C++. Here, the standard output stream represents the screen. It is also possible to redirect the output to other output devices. The

operator << is called the insertion or put to operator.

The iostream File

We have used the following #include directive in the program: #include <iostream>

The #include directive instructs the compiler to include the contents of the file enclosed within angular brackets into the source file. The header file iostream.h should be included at the beginning of all programs that use input/output statements.

Namespace

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the identifiers that are used in a program. For using the identifier defined in the namespace scope we must include the using directive, like

Using namespace std; Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI

C++ programs must include this directive. This will bring all the identifiers defined in std to the current global scope. Using and namespace are the new keyword of C++.

Return Type of main() In C++, main () returns an integer value to the operating system. Therefore, every main () in

C++ should end with a return (0) statement; otherwise a warning an error might occur. Since main () returns an integer type for main () is explicitly specified as int. Note that the default return type for all function in C++ is int.

Input Operator

The operator >> is known as extraction or get from operator. It extracts (or takes) the value from the keyboard and assigns it to the variable on its right fig 1.8. This corresponds to a familiar scanf() operation. Like <<, the operator >> can also be overloaded.

Cascading of I/O Operators We have used the insertion operator << repeatedly in the last two statements for printing

results. The statement

11 | P a g e

Cout << “Sum = “ << sum << “\n”; First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the newline character so that the next output will be in the new line. The multiple use of << in one

statement is called cascading. When cascading an output operator, we should ensure necessary blank spaces between different items. Using the cascading technique, the last two statements

can be combined as follows: Cout << “Sum = “ << sum << “\n” << “Average = “ << average << “\n”;

Variable declarations:

A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows:

type variable_list; Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or

any user-defined object, etc.

Group Type names* Notes on size / precision

Character types

Char Exactly one byte in size. At least 8 bits.

char16_t Not smaller than char. At least 16 bits.

char32_t Not smaller than char16_t. At least 32 bits.

wchar_t Can represent the largest supported character

set.

Integer types (signed)

signed char Same size as char. At least 8 bits.

signed short int Not smaller than char. At least 16 bits.

signed int Not smaller than short. At least 16 bits.

signed long int Not smaller than int. At least 32 bits.

signed long long int Not smaller than long. At least 64 bits.

Integer types

(unsigned)

unsigned char

(same size as their signed counterparts)

unsigned short int

unsigned int

unsigned long int

unsigned long long int

Floating-point types

Float

Double Precision not less than float

long double Precision not less than double

Boolean type Bool

Void type Void no storage

Null pointer decltype(nullptr)

Type sizes above are expressed in bits; the more bits a type has, the more distinct values it can represent, but at the same time, also consumes more space in memory:

Size Notes

8-bit = 28

12 | P a g e

16-bit = 216

32-bit = 232 (~4 billion)

64-bit = 264 (~18 billion billion)

Rules for naming variable ie variable_list

1. Variable names can range from 1 to 255 characters. To make variable names portable to other environments stay within a 1 to 31 character range.

2. All variable names must begin with a letter of the alphabet or an underscore( _ ).

3. After the first initial letter, variable names can also contain numbers. No spaces or special

characters are allowed.

4. Uppercase characters are distinct from lowercase characters. Using all uppercase letters is used primarily to identify constant variables.

5. You cannot use a C++ keyword (reserved word) as a variable name

Single Variable Declaration:

int int_Var;

float float_Var; double double_Var; bool bool_Var;

char char_Var;

Multiple Variables Declaration:

int i, j, k; char c, ch;

float f, salary; double d;

A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the

variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.

Scope of Variables

A scope is a region of the program and broadly speaking there are three places, where

variables can be declared: 1. Inside a function or a block which is called local variables.

2. In the definition of function parameters which is called formal parameters. 3. Outside of all functions which is called global variables.

1. 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. Following is the example using local variables:

#include <iostream>

using namespace std; void add(int a, int b)

{ int c; // Local variable as not know to main() c=a+b;

13 | P a g e

cout<<”The addition is : ”<<c; }

int main () {

// Local variable declaration: int a, b; // actual initialization

a = 10; b = 20;

add(a, b); return 0;

}

2. 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. Following is the example using global and local variables:

#include <iostream> using namespace std; // Global variable declaration:

int g;

int main () { // Local variable declaration:

int a, b; // actual initialization

a = 10; b = 20; g = a + b;

cout << g; return 0;

} A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

#include <iostream> using namespace std;

// Global variable declaration: int g = 20; int main ()

{ // Local variable declaration:

int g = 10; cout << g; return 0;

} When the above code is compiled and executed, it produces the following result: 10

3. References Variable

A reference variable is an alias, that is, another name for an already existing variable. Once a

14 | P a g e

reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. You cannot have NULL references. You must always be able to assume that a reference is

connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object.

Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Think of a variable name as a label attached to the variable's location in memory. You can

then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the

reference. For example, suppose we have the following example: int i = 17; We can declare reference variables for i as follows.

int& r = i; Read the & in these declarations as reference. Thus, read the first declaration as "r is an

integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following example makes use of references on int and double: #include <iostream>

using namespace std; int main ()

{ // declare simple variables int i;

double d; // declare reference variables

int& r = i; double& s = d; i = 5;

cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl;

d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl;

return 0; }

When the above code is compiled together and executed, it produces the following result: Value of i : 5 Value of i reference : 5

Value of d : 11.7 Value of d reference : 11.7

Constant Variables

It is simple in concept: variables declared with „const‟ added become constants and cannot be altered by the program.

It has three types: 1. Literals 2. Typed constant expression

3. Preprocessor definition 1. Literals: Literals are the most obvious kind of constants. They are used to express

particular values within the source code of a program. int a;

15 | P a g e

a=10; //10 is literal constant bool flag= true;

2. Typed Constant expression:

The value cannot be changed throughout the code. The keyword „Const‟is used Example:

#include <iostream> using namespace std;

const double pi = 3.14; const char tab = '\t';

int main () {

double rad=10.0; // radius double cir_circum;

cir_circum = 2 * pi * rad; cout << tab << “The Circumference of circle with radius ”

<<rad<<”is:”<<tab<<cir_circum; }

3. Preprocessor Definition:

#include <iostream>

using namespace std;

#define PI 3.14159 #define TAB '\t'

int main () {

double r=5.0; // radius double circle;

circle = 2 * PI * r; cout << circle;

cout << TAB; }

Default Parameters

A default parameter is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be used. If the user does supply a value for the default parameter, the user-supplied value is used.

Consider the following program: void PrintValues(int nValue1, int nValue2=10)

{ using namespace std; cout << "1st value: " << nValue1 << endl;

cout << "2nd value: " << nValue2 << endl; }

int main() {

16 | P a g e

PrintValues(1); // nValue2 will use default parameter of 10 PrintValues(3, 4); // override default value for nValue2 }

This program produces the following output: 1st value: 1

2nd value: 10 1st value: 3 2nd value: 4

Default parameters are an excellent option when the function needs a value that the user may or may not want to override

Note that it is impossible to supply a user-defined value for nValue3 without also supplying a value for nValue1 and nValue2. This is because C++ does not support a function call such as PrintValues(,,3). This has two major consequences:

1) All default parameters must be the rightmost parameters. The following is not allowed: void PrintValue(int nValue1=10, int nValue2); // not allowed

2) The leftmost default parameter should be the one most likely to be changed by the user. Function prototype-

A function prototype is a declaration of a function as opposed to its definition. While the definition of a function tells you what the function does, the prototype tells you how to

interface with the function. The prototype tells you the function's return type, its name, argument types. Syntax-

A general function prototype syntax is- return_type func_name (type param_name1, type param_name2, …,type param_nameN);

For example - void addition(num 1, num 2);

Function overloading-

If any class have multiple functions with same names but different parameters then they are

said to be overloaded. Methods to overload the function-

1. By having different types of arguments

For example- void print(int i)

{ cout << "Printing int: " << i << endl; }

void print(double f)

{ cout << "Printing float: " << f << endl; }

void print(char* c)

{ cout << "Printing character: " << c << endl; }

2. By changing number of arguments

For example-

17 | P a g e

int sum (int x , int y) { Cout << x+y;

}

int sum (int x , int y , int z) { Cout << x+y+z ;

}

Inline Functions

1. Need of Inline Function:

In C, one of the ways to preserve efficiency is through the use of macros, which allow

you to make what looks like a function call without the normal function call overhead. The macro is implemented with the preprocessor instead of the compiler proper, and the preprocessor replaces all macro calls directly with the macro code, so there‟s no cost involved

from pushing arguments, making an assembly- language CALL, returning arguments, and performing an assembly-language RETURN. All the work is performed by the preprocessor,

so you have the convenience and readability of a function call but it doesn‟t cost you anything.

There are two problems with the use of preprocessor macros in C++. The first is also

true with C: a macro looks like a function call, but doesn‟t always act like one. This can bury difficult-to- find bugs.

The second problem is specific to C++: the preprocessor has no permission to access class member data. This means preprocessor macros cannot be used as class member functions. To retain the efficiency of the preprocessor macro, but to add the safety and class

scoping of true functions, C++ has the inline function.

2. Introduction:

In solving the C++ problem of a macro with access to private class members, all the problems associated with preprocessor macros were eliminated. This was done by bringing

the concept of macros under the control of the compiler where they belong. C++ implements the macro as inline function, which is a true function in every sense. Any behavior you expect

from an ordinary function, you get from an inline function. The only difference is that an inline function is expanded in place, like a preprocessor macro, so the overhead of the function call is eliminated. Thus, you should (almost) never use macros, only inline functions.

Any function defined within a class body is automatically inline, but you can also make a non-class function inline by preceding it with the inline keyword. However, for it to

have any effect you must include the function body with the declaration, otherwise the compiler will treat it as an ordinary function declaration.

Thus,

inline int plusOne(int x);

has no effect at all other than declaring the function (which may or may not get an inline definition sometime later). The successful approach provides the function body:

inline int plusOne(int x){ return ++x; }

Notice that the compiler will check (as it always does) for the proper use of the

function argument list and return value (performing any necessary conversions), something the preprocessor is incapable of. Also, if you try to write the above as a preprocessor macro,

18 | P a g e

you get an unwanted side effect. You‟ll almost always want to put inline definitions in a header file. When the compiler sees such a definition, it puts the function type (the signature combined with the return value) and the function body in its symbol table. When you use the

function, the compiler checks to ensure the call is correct and the return value is being used correctly, and then substitutes the function body for the function call, thus eliminating the

overhead. The inline code does occupy space, but if the function is small, this can actually take less space than the code generated to do an ordinary function call (pushing arguments on the stack and doing the CALL).

An inline function in a header file has a special status, since you must include the header file containing the function and its definition in every file where the function is used,

but you don‟t end up with multiple definition errors (however, the definition must be identical in all places where the inline function is included). Example:

#include <iostream> using namespace std;

inline int Max(int x, int y) { return (x > y)? x : y;

} // Main function for the program

int main( ) { cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0; } Output:

Max (20,10): 20 Max (0,200): 200

Max (100,1010): 1010

3. Inlines inside classes

To define an inline function, you must ordinarily precede the function definition with

the inline keyword. However, this is not necessary inside a class definition. Any function you define inside a class definition is automatically an inline. For example:

// Inlines inside classes #include <iostream>

#include <string> using namespace std; class Point

{ int i, j, k;

public: Point(): i(0), j(0), k(0) {} Point(int ii, int jj, int kk)

: i(ii), j(jj), k(kk) {} void print(const string& msg = "") const

{ if(msg.size() != 0) cout << msg << endl;

19 | P a g e

cout << "i = " << i << ", "<< "j = " << j << ", "<< "k = " << k << endl; }

};

int main() {

Point p, q(1,2,3); p.print("value of p"); q.print("value of q");

}

Here, the two constructors and the print( ) function are all inlines by default. Notice in main( ) that the fact you are using inline functions is transparent, as it should be. The logical behavior of a function must be identical regardless of whether it‟s an inline (otherwise your compiler is

broken). The only difference you‟ll see is in performance.

Example of Default Argument in C++ Programming

/* Example to demonstrate the working of default arguments in C++ */

#include <iostream>

using namespace std; void Temp(int=5, float=5.5); /* Function Prototype with default arguments*/ int main()

{ cout<<"Result when no argument passed."<<endl; Temp(); /* Both default arguments from function prototype is used. */

cout<<"Result when integer argument is passed."<<endl; Temp(9); /* Only floating type default argument from function prototype is used. */

cout<<"Result when both arguments are passed."<<endl; Temp(9,9.4); /* Since both arguments are passed, default arguments will not be used. */ return 0;

} void Temp(int i, float f)

{ cout<<"Integer number: "<<i<<endl; cout<<"Decimal number: "<<f<<endl<<endl;

}

Output:

Result when no arguments passed.

Integer number: 5 Decimal number: 5.5

Result when integer argument is passed. Integer number: 9

Decimal number: 5.5

Result when both arguments are passed. Integer number: 9 Decimal number: 9.4

In case of first function call Temp(), no argument is passed. Thus, both integer and float

20 | P a g e

arguments from function prototype is used, i.e, both default argument is used. In case of second function call Temp(9), only integer argument is passed. Thus, the floating point argument from default argument is used as second parameter. In case of third function call

Temp(9), both integer and floating point argument is passed. Thus, default arguments specified in function prototype is not used.

Important Thing to Remember while Using Default Argument

The first argument in calling function can only be assigned to first argument in function definition. Similarly, second argument is assigned to second argument in function definition and so on. For example: If you use Temp(7.8) in the main() function, compiler

forcefully tries to convert that floating point value to integer value because the first argument in function definition is an integer.

Constant Arguments

When a function receives an argument, it performs one of two actions with regards to the value of the argument; it might modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that the function is not

supposed to alter the value of an argument, you should let the compiler know. This is a safeguard that serves at least two purposes. First, the compiler will make sure that the argument supplied stays intact; if the function tries to modify the argument, the compiler

would throw an error, letting you know that an undesired operation took place. Second, this speeds up execution.

To let the compiler know that the value of an argument must stay constant, use the const keyword before the data type of the argument. For example, if you declare a function like void Area(const string Side), the Area() function cannot modify the value of the Side

argument. Consider a function that is supposed to calculate and return the perimeter of a rectangle if it receives the length and the width from another function, namely main(). Here is

a program that would satisfy the operation (notice the Perimeter () function that takes two arguments):

#include <iostream> using namespace std;

float Perimeter(float l, float w) { double p;

p = 2 * (l + w); return p;

} int main() {

float length, width; cout << "Rectangle dimensions.\n";

cout << "Enter the length: "; cin >> length; cout << "Enter the width: ";

cin >> width; cout << "\nThe perimeter of the rectangle is: " << Perimeter(length, width) << "\n\n";

return 0; }

21 | P a g e

Output:

Rectangle dimensions. Enter the length: 35.55

Enter the width: 28.75

The perimeter of the rectangle is: 2044.12 The Perimeter() function does not change the values of the length or the width. To

reinforce the purpose of the assignment, you should make this clear to the compiler. To make

the length and the width arguments constant, you would change the declaration of the Perimeter() function as follows:

float Perimeter(const float l, const float w); You can make just one or more arguments constants, and there is no order on which arguments can be made constant.

Example:

#include <iostream> using namespace std; // Rectangle

double MomentOfInertia(const double b, const double h) {

return b * h * h * h / 3; } // Semi-Circle

double MomentOfInertia(const double R) {

const double PI = 3.14159; return R * R * R * R * PI/ 8;

}

// Triangle double MomentOfInertia(const double b, const double h, int)

{ return b * h * h * h / 12; }

int main() {

double base = 7.74, height = 14.38, radius = 12.42;

cout << "Rectangle\n"<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(base, height) << "mm\n\n"; cout << "Semi-Circle\n"<< "Moment of inertia with regard to the X axis: ";

cout << "I = " << MomentOfInertia(radius) << "mm\n\n";

cout << "Triangle\n"<< "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n";

22 | P a g e

return 0; }

Formatting and I/O manipulators

MANIPULATORS

Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer‟s choice of display.

There are numerous manipulators available in C++. Some of the more commonly used manipulators are provided here below:

Stream manipulators

Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example:

cout << boolalpha;

They are still regular functions and can also be called as any other function using a stream object as argument, for example:

boolalpha (cout);

Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters.

Output manipulators

endl – Insert newline and flush

ends – Insert null character

flush – Flush stream buffer

Parameterized manipulators

These functions take parameters when used as manipulators. They require the explicit inclusion of the header file<iomanip>.

resetiosflags Clears the specified flags.

setbase Set base for integers.

setfill Sets the character that will be used to fill spaces in a right-justified display.

setiosflags Sets the specified flags.

setprecision Sets the precision for floating-point values.

setw Specifies the width of the display field.

endl Manipulator:

This manipulator has the same functionality as the „\n‟ newline character.

For example:

23 | P a g e

cout << "Exforsys" << endl; cout << "Training";

Output:

Exforsys

Training

setw Manipulator:

This manipulator sets the minimum field width on output. The syntax is:

setw(x)

Here setw causes the number or string that follows it to be printed within a field of x

characters wide and x is the argument set in setw manipulator. The header file that must be

included while using setw manipulator is <iomanip.h>

#include <iostream.h> #include <iomanip.h>

void main( ) {

int x1=12345,x2= 23456, x3=7892; cout << setw(8) << ”Exforsys” << setw(20) << ”Values” << endl << setw(8) << “E1234567” << setw(20)<< x1 << end

<< setw(8) << “S1234567” << setw(20)<< x2 << end << setw(8) << “A1234567” << setw(20)<< x3 << end;

}

The output of the above example is:

setw(8) setw(20)

Exforsys Values E1234567 12345 S1234567 23456

A1234567 7892

setfill Manipulator:

This is used after setw manipulator. If a value does not entirely fill a field, then the character specified in the setfill argument of the manipulator is used for filling the fields.

#include <iostream.h> #include <iomanip.h>

void main( ) { cout << setw(10) << setfill('$') << 50 << 33 << endl;

}

The output of the above program is

$$$$$$$$5033

This is because the setw sets 10 width for the field and the number 50 has only 2 positions in it. So the remaining 8 positions are filled with $ symbol which is specified in the setfill argument.

24 | P a g e

setprecision Manipulator:

The setprecision Manipulator is used with floating point numbers. It is used to set the number of digits printed to the right of the decimal point. This may be used in two forms:

fixed

scientific

These two forms are used when the keywords fixed or scientific are appropriately used before the setprecision manipulator. The keyword fixed before the setprecisionmanipulator prints the floating point number in fixed notation. The keyword scientific before the setprecision

manipulator prints the floating point number in scientific notation.

#include <iostream.h> #include <iomanip.h> void main( )

{ float x = 0.1;

cout << fixed << setprecision(3) << x << endl; cout << sceintific << x << endl; }

The above gives ouput as:

0.100 1.000000e-001

Basic Input/Output

C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen, the keyboard or a file. A stream is an entity

where a program can either insert or extract characters to/from. There is no need to know details about the media associated to the stream or any of its internal specifications. All we

need to know is that streams are a source/destination of characters and that these characters are provided/accepted sequentially (i.e., one after another). The standard library defines a handful of stream objects that can be used to access what are

considered the standard sources and destinations of characters by the environment where the program runs:

stream description

cin standard input stream

cout standard output stream

cerr standard error (output) stream

clog standard logging (output) stream

We are going to see in more detail only cout and cin (the standard output and input streams); cerr and clog are also output streams, so they essentially work like cout, with the only

difference being that they identify streams for specific purposes: error messages and logging; which, in many cases, in most environment setups, they actually do the exact same thing: they

print on screen, although they can also be individually redirected.

1. Standard output (cout)

On most program environments, the standard output by default is the screen, and the

25 | P a g e

C++ stream object defined to access it is cout. For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen

cout << 120; // prints number 120 on screen cout << x; // prints the value of x on screen

The << operator inserts the data that follows it into the stream that precedes it. In the examples above, it inserted the literal string Output sentence, the number 120, and the value of variable x into the standard output stream cout. Notice that the sentence in the first

statement is enclosed in double quotes (") because it is a string literal, while in the last one, x is not. The double quoting is what makes the difference; when the text is enclosed between

them, the text is printed literally; when they are not, the text is interpreted as the identifier of a variable, and its value is printed instead. For example, these two sentences have very different results:

cout << "Hello"; // prints Hello

cout << Hello; // prints the content of variable Hello

Multiple insertion operations (<<) may be chained in a single statement:

cout << "This " << " is a " << "single C++ statement";

This last statement would print the text This is a single C++ statement. Chaining insertions is especially useful to mix literals and variables in a single statement:

cout << "I am " << age << " years old and my zipcode is " << zipcode;

Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the output of the previous statement would be:

I am 24 years old and my zipcode is 90064

What cout does not do automatically is add line breaks at the end, unless instructed to

do so. For example, take the following two statements inserting into cout: cout << "This is a sentence."; cout << "This is another sentence.";

The output would be in a single line, without any line breaks in between. Something like: This is a sentence.This is another sentence.

To insert a line break, a new-line character shall be inserted at the exact position the line should be broken. In C++, a new-line character can be specified as \n (i.e., a backslash character followed by a lowercase n). For example:

cout << "First sentence.\n"; cout << "Second sentence.\nThird sentence.";

This produces the following output:

First sentence.

Second sentence. Third sentence.

26 | P a g e

Alternatively, the endl manipulator can also be used to break lines. For example:

cout << "First sentence." << endl; cout << "Second sentence." << endl;

This would print:

First sentence. Second sentence.

The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an additional behavior: the stream's buffer (if any) is flushed, which

means that the output is requested to be physically written to the device, if it wasn't already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only when flushing the stream would be a feature

and '\n' when it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some devices it may produce a delay.

2. Standard input (cin)

In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.

For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example:

int age; cin >> age;

The first statement declares a variable of type int called age, and the second extracts from cin a value to be stored in it. This operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the

keyboard. In this case, note that the characters introduced using the keyboard are only transmitted to the program when the ENTER (or RETURN) key is pressed. Once the

statement with the extraction operation on cin is reached, the program will wait for as long as needed until some input is introduced.

The extraction operation on cin uses the type of the variable after the >> operator to determine how it interprets the characters read from the input; if it is an integer, the format expected is a

series of digits, if a string a sequence of characters, etc.

// i/o example

#include <iostream> using namespace std;

int main () {

int i; cout << "Please enter an integer value: ";

cin >> i; cout << "The value you entered is " << i;

27 | P a g e

cout << " and its double is " << i*2 << ".\n"; return 0; }

Output

Please enter an integer value: 702 The value you entered is 702 and its double is 1404.

As you can see, extracting from cin seems to make the task of getting input from the standard input pretty simple and straightforward. But this method also has a big drawback.

What happens in the example above if the user enters something else that cannot be interpreted as an integer? Well, in this case, the extraction operation fails. And this, by default, lets the program continue without setting a value for variable i, producing undetermined

results if the value of i is used later.

This is very poor program behavior. Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately. Only very simple programs should rely on values extracted directly from cin without further checking. A little

later we will see how stringstreams can be used to have better control over user input. Extractions on cin can also be chained to request more than one datum in a single statement:

cin >> a >> b;

This is equivalent to:

cin >> a;

cin >> b;

In both cases, the user is expected to introduce two values, one for variable a, and

another for variable b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a tab, or a new-line character.

New and delete operators

Dynamic memory

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the

memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Operators new and new[]

Dynamic Memory allocated using operator new. new is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It

returns a pointer to the beginning of the new block of memory allocated. Its syntax is:

pointer = new type pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one single element of type type.

28 | P a g e

The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:

int * foo;

foo = new int [5];

In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer). Therefore, foo now points to a valid block of memory with space for five elements of type int.

Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent). The second element can be

accessed either with foo[1] or *(foo+1), and so on...

There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of memory using new. The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the

moment of designing the program, before it is run, whereas the dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.

The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore,

there are no guarantees that all requests to allocate memory using operator new are going to be granted by the system.

C++ provides two standard mechanisms to check if the allocation was successful:

One is by handling exceptions. Using this method, an exception of type bad_alloc is thrown when the allocation fails. Exceptions are a powerful C++ feature explained later in these

tutorials. But for now, you should know that if this exception is thrown and it is not handled by a specific handler, the program execution is terminated.

This exception method is the method used by default by new, and is the one used in a declaration like:

foo = new int [5]; // if allocation fails, an exception is thrown

The other method is known as nothrow, and what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its

execution normally.

This method can be specified by using a special object called nothrow, declared in header <new>, as argument for new:

29 | P a g e

foo = new (nothrow) int [5];

In this case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer:

1 2 3

4 5

int * foo; foo = new (nothrow) int [5]; if (foo == nullptr) {

// error assigning memory. Take measures. }

This nothrow method is likely to produce less efficient code than exceptions, since it implies

explicitly checking the pointer value returned after each and every allocation. Therefore, the exception mechanism is generally preferred, at least for critical allocations. Still, most of the

coming examples will use the nothrow mechanism due to its simplicity.

Operators delete and delete[]

In most cases, memory allocated dynamically is only needed during specific periods of time

within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of operator delete,

whose syntax is:

delete pointer; delete[] pointer;

The first statement releases the memory of a single element allocated using new, and the

second one releases the memory allocated for arrays of elements using new and a size in brackets ([]). The value passed as argument to delete shall be either a pointer to a memory block previously

allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).

// rememb-o-matic

#include <iostream> #include <new> using namespace std;

int main ()

{ int i,n; int * p;

cout << "How many numbers would you like to type? "; cin >> i;

p= new (nothrow) int[i]; if (p == nullptr) cout << "Error: memory could not be allocated";

else {

for (n=0; n<i; n++) {

30 | P a g e

cout << "Enter number: "; cin >> p[n]; }

cout << "You have entered: "; for (n=0; n<i; n++)

cout << p[n] << ", "; delete[] p; }

return 0; }

Output: How many numbers would you like to type? 5

Enter number : 75 Enter number : 436

Enter number : 1067 Enter number : 8 Enter number : 32

You have entered: 75, 436, 1067, 8, 32,

Notice how the value within brackets in the new statement is a variable value entered by the user (i), not a constant expression:

p= new (nothrow) int[i];

There always exists the possibility that the user introduces a value for i so big that the system

cannot allocate enough memory for it. For example, when I tried to give a value of 1 billion to the "How many numbers" question, my system could not allocate that much memory for the program, and I got the text message we prepared for this case (Error: memory could not be

allocated). It is considered good practice for programs to always be able to handle failures to

allocate memory, either by checking the pointer value (if nothrow) or by catching the proper exception.

Defining a class:

The main purpose of C++ programming is to add object orientation to the C programming

language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and

methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

C++ Class Definitions:

When you define a class, you define a blueprint for a data type. 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.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the

keyword class as follows:

31 | P a g e

class Box { public:

double length; // Length of a box double breadth; // Breadth of a box

double height; // Height of a box };

The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the

class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

Define C++ Objects:

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of

basic types. Following statements declare two objects of class Box: Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members

Accessing Public Data Members:

The public data members of objects of a class can be accessed using the direct member access

operator (.). Let us try the following example to make the things clear: #include <iostream>

using namespace std; class Box

{ public: double length; // Length of a box

double breadth; // Breadth of a box double height; // Height of a box

}; int main( ) {

Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box

double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0;

Box1.length = 6.0; Box1.breadth = 7.0;

// box 2 specification Box2.height = 10.0;

Box2.length = 12.0; Box2.breadth = 13.0;

32 | P a g e

// volume of box 1 volume = Box1.height * Box1.length * Box1.breadth; cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2 volume = Box2.height * Box2.length * Box2.breadth;

cout << "Volume of Box2 : " << volume <<endl; return 0; }

When the above code is compiled and executed, it produces the following result: Volume of Box1 : 210 Volume of Box2 : 1560

It is important to note that private and protected members cannot be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

Accessing Private Data Members:

To access, use and initialize the private data member you need to create getter and setter functions, to get and set the value of the data member.

The setter function will set the value passed as argument to the private data member, and the getter function will return the value of the private data member to be used. Both getter and

setter function must be defined public.

Example :

class Student

{ private: // private data member

int rollno; public: // public accessor and mutator functions

int getRollno() {

return rollno; }

void setRollno(int i) {

rollno=i; }

};

int main() { Student A;

A.rollono=1; //Compile time error cout<< A.rollno; //Compile time error

A.setRollno(1); //Rollno initialized to 1 cout<< A.getRollno(); //Output will be 1

}

33 | P a g e

So this is how we access and use the private data members of any class using the getter and setter methods. We will discuss this in more details later.

Accessing Protected Data Members

Protected data members, can be accessed directly using dot (.) operator inside the subclass of the current class, for non-subclass we will have to follow the steps same as to access private data member.

Member functions

The functions under any class are known as member functions or members. There are two types of members:

Inline member functions The functions which are defined inside the class body Outline member functions

The functions which are defines in class but body is outside the class.

Example: #include <iostream> using namespace std;

class Box {

public: double length; // Length of a box double breadth; // Breadth of a box

double height; // Height of a box

// Member functions declaration double getVolume(void); void setLength( double len );

void setBreadth( double bre ); void setHeight( double hei );

}; // Member functions definitions

double Box::getVolume(void) {

return length * breadth * height; } void Box::setLength( double len )

{ length = len;

} void Box::setBreadth( double bre ) {

breadth = bre; }

void Box::setHeight( double hei ) { height = hei;

} // Main function for the program

34 | P a g e

int main( ) { Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here

// box 1 specification Box1.setLength(6.0);

Box1.setBreadth(7.0); Box1.setHeight(5.0);

// box 2 specification Box2.setLength(12.0);

Box2.setBreadth(13.0); Box2.setHeight(10.0);

// volume of box 1 volume = Box1.getVolume();

cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl;

return 0; }

Access Specifiers In C++

Private access:

All members regardless of their access level are accessible in the class in which they are declared, the enclosing class. This is the only place where private members can be

accessed.

Protected access:

A protected member can also be accessed from inside a derived class, but it cannot be reached from an unrelated class.

Public access

Public access gives unrestricted access from anywhere in the code.

#include<iostream>

#include<conio.h> using namespace std; class Declare

{ private:

int a = 10; public: int b = 20;

protected: int c = 30;

public: void call()

35 | P a g e

{ cout<<"Declare variable values"<<endl; //Every members can be access as all are in the same class

cout<<"Value of a = "<<a<<endl; cout<<"Value of b = "<<b<<endl;

cout<<"Value of c = "<<c<<endl; } };

class Inherit:public Declare

{ public: void call()

{ cout<<"\nInherit variable values"<<endl;

//As 'a' is private member so 'a' cannot be accessed by another class //cout<<"Value of a = "<<a<<endl; //'b' is declared as public, so it can be accessed from any class which is inherited

cout<<"Value of b = "<<b<<endl; //'c' is declared as protected, so it can be accessed from class which is inherited

cout<<"Value of c = "<<c<<endl; } };

int main()

{ Declare d; d.call();

Inherit i; //= new Inherit();

i.call(); cout<<"\nAccessing variable of declare outside declare class"<<endl;

//'a' cannot be accessed as it is private //cout<<"value of a = "<<d.a<<endl;

//'b' is public as can be accessed from any where cout<<"value of b = "<<d.b<<endl;

//'c' is protected and cannot be accesed here

//cout<<"value of c = "<<d.c<<endl; }

Output:

Declare variable values Value of a = 10 Value of b = 20

Value of c = 30

Inherit variable values Value of b = 20

36 | P a g e

Value of c = 30 Accessing variable of declare outside declare class

value of b = 20

Static member function:

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution

operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

Example:-

#include <iostream> using namespace std;

class Box {

public: static int objectCount;

// Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) {

cout <<"Constructor called." << endl; length = l;

breadth = b; height = h; // Increase every time object is created

objectCount++; }

double Volume() { return length * breadth * height;

} static int getCount()

{ return objectCount; }

private: double length; // Length of a box

double breadth; // Breadth of a box double height; // Height of a box };

// Initialize static member of class Box

37 | P a g e

int Box::objectCount = 0; int main(void)

{

// Print total number of objects before creating object. cout << "Inital Stage Count: " << Box::getCount() << endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects after creating object. cout << "Final Stage Count: " << Box::getCount() << endl;

return 0;

} This pointer

The „this‟ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. „this‟ pointer is a constant pointer that holds the memory address of the current object. „this‟ pointer is not

available in static member functions as static member functions can be called without any object (with class name). For a class X, the type of this pointer is „X* const‟. Also, if a member function of X is

declared as const, then the type of this pointer is „const X *const‟ (see this GFact)

Following are the situations where „this‟ pointer is used:

1) When local variable’s name is same as member’s name #include<iostream>

using namespace std;

/* local variable is same as a member's name */ class Test {

private: int x;

public: void setX (int x) {

// The 'this' pointer is used to retrieve the object's x // hidden by the local variable 'x'

this->x = x; } void print() { cout << "x = " << x << endl; }

};

int main() { Test obj;

int x = 20; obj.setX(x);

obj.print();

38 | P a g e

return 0; }

Output: x = 20

For constructors, initializer list can also be used when parameter name is same as member‟s name.

2) To return reference to the calling object /* Reference to the calling object can be returned */

Test& Test::func () {

// Some processing return *this; }

When a reference to a local object is returned, the returned reference can be used to chain

function calls on a single object. #include<iostream>

using namespace std; class Test

{ private:

int x; int y; public:

Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; }

Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } };

int main()

{ Test obj1(5, 5);

// Chained function calls. All calls modify the same object // as the same object is returned by reference

obj1.setX(10).setY(20); obj1.print();

return 0; }

Output: x = 10 y = 20 Constructors

Introduction to Constructors:

Constructors are special member functions which are having some different properties than

that of the normal member functions of C++ class. They are special because they shares exactly same name as that of class name and they gets called automatically when the object of corresponding class is created in memory.

39 | P a g e

In other words it means that constructor is invoked whenever the object of associated class is created. It‟s called constructor because it construct the values of data members of class. A constructor is declared and defined as :

class Sample

{ int a, b; public:

Sample(); };

Sample :: Sample () { a=0; b=0;

}

When a class contains a constructor like the defined one above, it is guaranteed that an object created by class will initialized automatically For example

Sample S;

It will not only creates the object S of type Sample but also initializes its data members a & b to zero. A constructor with no parameter is called as the default constructor. If no constructor is

defined then the complier supplies a default constructor.

Some special characteristics of constructors are given below:

(i) These are called automatically when the objects are created. (ii) All objects of the class having a constructor are initialized before some use. (iii) These should be declared in the public section for availability to all the functions.

(iv) Return type (not even void) cannot be specified for constructors. (v) These cannot be inherited, but a derived class can call the base class constructor.

(vi) These cannot be static. (vii) The make implicit calls to the memory allocation and deallocation operators new and

delete

(viii) These cannot be virtual. (ix) Default and copy constructors are generated by the compiler wherever required.

Generated constructors are public. (x) These can have default arguments as other C++ functions. (xi) A constructor can call member functions of its class.

(xii) An object of a class with a constructor cannot be used as a member of a union. (xiii) A constructor can call member functions of its class.

(xiv) We can use a constructor to create new objects of its class type by using the syntax.

Name_of_the_class (expresson_list)

For example,

Employee obj3 = obj2; // see program 10.5

Or even

40 | P a g e

Employee obj3 = employee (1002, 35000); //explicit call

Types of Constructors:

Constructors are of three types: 1. Default Constructor

2. Parameterized Constructor 3. Copy Constructor

1. Default Constructor: Default constructor is the constructor which doesn't take any argument. It has no parameter.

class Cube {

int side; public:

Cube() { side=10;

} };

int main() { Cube c;

cout << c.side; }

2. Parameterized Constructor: These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by

passing the appropriate values as argument.

class Cube

{

int side;

public: Cube(int x)

{ side=x;

}

}; int main()

{ Cube c1(10); Cube c2(20);

Cube c3(30); cout << c1.side;

cout << c2.side; cout << c3.side;

}

41 | P a g e

3. Copy Constructor: These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.

Class fun {

Float x,y; Public:

Fun (floata,float b)//constructor

{ x = a;

y = b; }

Fun (fun &f) //copy constructor

{ cout<<”\ncopy constructor at work\n”;

X = f.x; Y = f.y;

}

Void display (void) {

cout<<””<<y<<end1; }

};

Destructors

Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.

The syntax for destructor is same as that for the constructor; the class name is used for the name of destructor; with a tilde ~ sign as prefix to it.

class A {

public:

~A(); };

Some of the characteristics associated with destructors are :

(i) These are called automatically when the objects are destroyed.

(ii) Destructor functions follow the usual access rules as other member functions. (iii) These de-initialize each object before the object goes out of scope. (iv) No argument and return type (even void) permitted with destructors.

(v) These cannot be inherited. (vi) Static destructors are not allowed.

(vii) Address of a destructor cannot be taken. (viii) A destructor can call member functions of its class. (ix) An object of a class having a destructor cannot be a member of a union.

Friend Function

One of the important concepts of OOP is data hiding, i.e., a nonmember function cannot access an object's private or protected data.

But, sometimes this restriction may force programmer to write long and complex codes.

42 | P a g e

So, there is mechanism built in C++ programming to access private or protected data from non-member function which is friend function and friend class.

If a function is defined as a friend function then, the private and protected data of class can be accessed from that function.

The complier knows a given function is a friend function by its keyword friend.

The declaration of friend function should be made inside the body of class (can be

anywhere inside class either in private or public section) starting with keyword friend.

class class_name

{ ..... .... ........

friend return_type function_name(argument/s); ...... .... ........

}

Now, you can define friend function of that name and that function can access the private and protected data of that function.

No keywords in used in function definition of friend function.

Friend classes:

Similar to friend functions, a friend class is a class whose members have access to the private

or protected members of another class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the

condition that the friend becoming class must be first declared or defined (forward declaration).

Program Illustrating the Friend Class

// friend class #include <iostream> using namespace std;

class Square;

class Rectangle {

int width, height; public:

int area () {

return (width * height); }

void convert (Square a); };

class Square {

friend class Rectangle; private: int side;

43 | P a g e

public: Square (int a) : side(a) {} };

void Rectangle::convert (Square a) {

width = a.side; height = a.side; }

int main () {

Rectangle rect; Square sqr (4); rect.convert(sqr);

cout << rect.area(); return 0;

} In this example, class Rectangle is a friend of class Square allowing Rectangle's member

functions to access private and protected members of Square. More concretely, Rectangle accesses the member variable Square::side, which describes the side of the square.

There is something else new in this example: at the beginning of the program, there is an empty declaration of class Square. This is necessary because class Rectangle uses Square (as a

parameter in member convert), and Square uses Rectangle (declaring it a friend).

Friendships are never corresponded unless specified: In our example, Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the protected and private members of Square but

not the other way around. Of course, Square could also be declared friend of Rectangle, if needed, granting such an access.

Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.

What is Allocation of memory?

There are two ways that memory gets allocated for data storage:

1. Compile Time (or static) Allocation

o Memory for named variables is allocated by the compiler

o Exact size and type of storage must be known at compile time

o For standard array declarations, this is why the size has to be constant

2. Dynamic Memory Allocation

o Memory allocated "on the fly" during run time

o dynamically allocated space usually placed in a program segment known as the heap or the free store

o Exact amount of space or number of items does not have to be known by the compiler in advance.

o For dynamic memory allocation, pointers are crucial

44 | P a g e

Why dynamic Programming?

All memory needs were determined before program execution by defining the

variables needed. But there may be cases where the memory needs of a program can only be determined during runtime.

For example, when the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Steps for dynamic memory allocation:

1. Creating the dynamic space.

2. Storing its address in a pointer (so that the space can be accesed)

Allocating space with new:

To allocate space dynamically, use the unary operator new, followed by the type being allocated.

newint; // dynamically allocates an int new double; // dynamically allocates a double

If creating an array dynamically, use the same form, but put brackets with a size after the type: newint[40]; // dynamically allocates an array of 40 ints

new double[size]; // dynamically allocates an array of size doubles // note that the size can be a variable

These statements above are not very useful by themselves, because the allocated spaces have no names! BUT, the new operator returns the starting address of the

allocated space, and this address can be stored in a pointer: int * p; // declare a pointer p

p = new int; // dynamically allocate an int and load address into p double * d; // declare a pointer d

d = new double; // dynamically allocate a double and load address into d

// we can also do these in single line statements int x = 40; int * list = new int[x];

float * numbers = new float[x+10];

Accessing dynamically created space:

So once the space has been dynamically allocated, how do we use it?

For single items, we go through the pointer. Dereference the pointer to reach the dynamically created target: int * p = new int; // dynamic integer, pointed to by p *p = 10; // assigns 10 to the dynamic integer

cout<< *p; // prints 10

For dynamically created arrays, you can use either pointer-offset notation, or treat the pointer as the array name and use the standard bracket notation:

double * numList = new double[size]; // dynamic array for (int i = 0; i < size; i++)

numList[i] = 0; // initialize array elements to 0 numList[5] = 20; // bracket notation *(numList + 7) = 15; // pointer-offset notation

45 | P a g e

// means same as numList[7] Deallocation of dynamic memory:

To deallocate memory that was created with new, we use the unary operator delete.

The one operand should be a pointer that stores the address of the space to be deallocated:

int * ptr = new int; // dynamically created int // ... deleteptr; // deletes the space that ptr points to

Note that the pointer ptr still exists in this example. That's a named variable subject to scope and extent determined at compile time. It can be reused:

ptr = new int[10]; // point p to a brand new array To deallocate a dynamic array, use this form: delete [] name_of_pointer;

Example: int * list = new int[40]; // dynamic array

delete [] list; // deallocates the array list = 0; // reset list to null pointer

After deallocating space, it's always a good idea to reset the pointer to null unless you are

pointing it at another valid target right away.

Array of Object:

#include<iostream>

using namespace std; class c1

{ int m; int n;

public: c1(into, intp) // Simple constructor with 2 arguments

{ m=o; n=p;

} int inputn() {returnn;} //Method definition

int inputm() {returnm;} // Function definition }; int main() // Main method

{ cl objj[3] = { cl(2, 2),cl(2, 3),cl(4, 5)};

int n; for(n=0;n<3;n++) {

cout<<objj[n].inputm(); // Output display cout<< ",";

cout<<objj[n].inputn() << "\n"; }

46 | P a g e

return0; }

Pointers:

A pointer variable (or pointer in short) is basically the same as the other variables,

which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address. Pointers are extremely powerful because they allows you to access addresses and manipulate

their contents. But they are also extremely complex to handle. Using them correctly, they could greatly improve the efficiency and performance. On the other hand, using them

incorrectly could lead to many problems, from un-readable and un-maintainable codes, to infamous bugs such as memory leaks and buffer overflow, which may expose your system to hacking.

Declaration and initialization of Pointers:

Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int anddouble) too.

Type *ptrname e.g:

int *p; int b=10; p=&b;

Creating the Source File Like C programs can be created using any text editor. Foe example, on the UNIX, we can use vi or ed text editor for creating using any text editor for creating and editing the source code.

On the DOS system, we can use endlin or any other editor available or a word processor system under non-document mode.

Some systems such as Turboc C++ provide an integrated environment for developing and editing programs The file name should have a proper file extension to indicate that it is a C++ implementations

use extensions such as .c,.C, .cc, .cpp and .cxx. Turboc C++ and Borland C++ use .c for C programs and .cpp(C plus plus) for C++ programs. Zortech C++ system use .cxx while UNIX

AT&T version uses .C (capital C) and .cc. The operating system manuals should be consulted to determine the proper file name extension to be used.

Compiling and Linking The process of compiling and linking again depends upon the operating system. A few

popular systems are discussed in this section. Unix AT&T C++ This process of implementation of a C++ program under UNIX is similar to that of a C

program. We should use the “cc” (uppercase) command to compile the program. Remember, we use lowercase “cc” for compiling C programs. The command

CC example.C At the UNIX prompt would compile the C++ program source code contained in the file example.C. The compiler would produce an object file example.o and then automatically link

with the library functions to produce an executable file. The default executable filename is a.

out.

A program spread over multiple files can be compiled as follows: CC file1.C file2.o

47 | P a g e

The statement compiles only the file file1.C and links it with the previously compiled file2.o file. This is useful when only one of the files needs to be modified. The files that are not modified need not be compiled again.

Turbo C++ and Borland C++ Turbo C++ and Borland C++ provide an integrated program development environment under

MS DOS. They provide a built-in editor and a menu bar includes options such as File, Edit, Compile and Run. We can create and save the source files under the File option, and edit them under the Edit

option. We can then compile the program under the compile option and execute it under the Run option. The Run option can be used without compiling the source code.