for in C++ - myhuts

shrewdnessfreedomSoftware and s/w Development

Dec 2, 2013 (3 years and 11 months ago)

307 views

Structured Programming

* It splits the tasks into modular forms. This makes the program simpler and easier

* In structured programming the flow of program execution is based on the

structure of the program.

* Information hiding as it relates to data is
less in structured programming.

* Structured programming passes data around in the form of function arguments.

* Structured programming follows top
-
to
-
bottom approach.


Object Oriented Programming


* Object
oriented

programming is a programming language wh
ich organize around objects and data.

* OOP Programming is developed in 1960's.

* OOP programming mainly based on three concepts classes, objects and methods.

* OOP also
supports

inheritance, polymorphism....

* Information hiding as it relates to data is h
igh in Object Oriented programming.

* Object oriented programming follows bottom
-
to
-
top approach.


Object: Objects are basic runtime entities

Class: Class

is a collection of objects with similar datatype.


(or)

A class is a user defined datatype in which we can define both data

members and member functions.

Data encapsulation: The wrapping up of data and functions into single unit.

Data
abstraction: Refers

to the act of representing essential features without

inc
luding the backg
round details and
explanations.

Inheritance: Inheritance

is the process by which objects of one class acquires

the properti
es of objects of another
class.

Polymorphism: Ability to take more than one form. Poly means many and morphism means
forms.

Dynamic
Binding: Binding

refers to the linking of procedure call to the code to

be executed. Dynamic binding refers
given procedure call is not known until the

runtime

Message Passing:

set of objects communicate with
each other
.


1. Creating classes

that define objects and
behavior
.


2. Creating objects from class definitions.


3. Establishing communication among objects.

Benefits

of OOPS
:

1. It supports both structured programming and
object

programming

2. It gives the easiest way to
data hiding

by the words
class, public
,
and private
.

3. Inheritance.

4. Overloading of functions and operators.

5.
Class

templates and function templates.

6. Exception handling.

7. Constructors, destructors, friends.




Applications of OOPS
:

1. Realtime systems.

2. Simulation and modelling.

3. Object oriented database systems.

4. Artificial Intelligance and expert systems.

5. Neural network and parallel programming.

6. CAD/CAM systems.

C++ Brief History
:


* c++ is an object oriented programming language. Initially

named with


'c with classes'.

* c++ was developed by Bjarne Storustrup at AT&T Bell Laboratories in the early


80's.

* c++ is a superset of c. c++ is an extension with a major addition of class


construct.

* Finally the name changed to c++ in 1983.

Di
fferences between C and C++
:

C

1. Emphasis is on doing things [algorithms]

2. Large programs are divided into smaller programs known as functions.

3. Most of functions share global data.

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

5.
Functions transform data from one form to another.

6. Employs top down approach.


C++

1. Emphasis is on data rather than procedure.

2. Programs are divided into what are known as objects.

3. New data and functions can be added whereever necessary.

4. Data
is hidden and can't be accessed by external functions.

5. Object may communicate with each other through functions.

6. Employs bottom up approach.

Why C++ become popular?

* It supports all features of both structured programming and object oriented

program
ming.

* It gives easiest way to handle the data hiding and encapsulation with the help cof powerful keywords such as


class, private, public and protected.

* Inheritance, one of the most powerful design concepts is supported with single inheritance and
multiple



inheritance of base and derived classes.

* Polymorphism through virtual functions, virtual base classes and virtual destructors gives the late binding of the



computer.

* It provides overloading of operators and functions.

* C++ focuses o
n function and class templates for handling parameterized dat
a

types.

* Exception handling is done by the extra keywords namely, try, catch and throw.

* C++ provides friends, static mehtods, constructors destructors for the class objects.



Data Types:





C++ Arithematic Operators
:


+

Addition


-

Subtraction


*

Multiplication


/

Division


%

Modulo

C++ Assignment Operators
:


=
Assign right hand side value to the left hand side


+=

Value of LHS variable will be added to the RHS and assign it back to the
variable

in LHS


-
=
Value of LHS variable will be subtracted to the RHS and assign it back to the
variable

in LHS


*=
Value of LHS variable will be multiplied to the RHS and assign it back to the
variable

in LHS


/=

Value of LHS variable will be divided to t
he RHS and assign it back to the
variable

in LHS


%=
The
remainder

will be stored back to the LHS after integer division carried out between the LHS variable and


the RHS variable


>>=

Right shift and assign to the LHS


<<=

Left shift and assign to
the LHS


&=

Bitwise AND operation and assign to the LHS


|=

Bitwise OR operation and assign to the LHS


~=

Bitwise complement and assign to the LHS

C++ Comparision And Logical Operators

Relational Operators


<

Lessthan


>

Greaterthan


<=

Lessthan

or equal to


>=

Greater than or equal to

==

Equal to


!=

not equal to

Logical Operators


&&

Logical AND


||

Logical OR


!

Not


C++ Bitwise Operators
:


&

bitwise AND


|

bitwise inclusive OR


^

bitwise exclusive OR(XOR)


>>

bitwise right shift


<<

bitwis
e left shift


~

bitwise complement

C++ Special Operators
:

Unary Operators


*


Contents of the storage fiels to which a pointor is pointing


&


Address of a variable


-


Negative value


!


Negation(0 if value not equal to 0; 1 if value=0)


~


Bitwise
complement


++


Incrementer


--



Decrementer


type


Forced type of conversion

sizeof


size of the subsequent data type or type in byte


Ternary Operator:

C++ includes ternary or conditional operator. It is called

ternary because it us
es three expressions. The ternary operator acts like a

shorthand version of the if
-
else construction.


exp1?exp2:exp3


comma operator:


C++ uses comma operator in two ways. The first use is as a

separator

in the variable declaration.

And the second

one is as an operator
in an expression for loop.


Scope Operator:

The double colon


:: is used as the scope resolution operatorin C++. The scoping operator is also used in a class
member function definition. The scope operator can also be used to differe
ntiate between

members of base classes
with identical names.New and delete operators: Memory is allocated by new operator and memory is

deallocated
by delete operator.

Strucutre of C++ program
:

include files

class declarations

class function definitions

main function program


The iostream.h file: #include<iostream.h>

This directive causes the preprocessor to add the contents

of the iostream.h file to the program.


It contains declarations for the identifiers cout and the operator <<,

cin and the operator
>>


output operator <<: << is called insertion or put operator.


cout<<"welcome";

input operator >>: >> is called extraction or get from operator.


cin>>a;

C++ Tokens
:

Tokens:

The smallest individual units in a program are known as tokens. c++ has

following tokens.

* Keywords: Keywords implement specific c++ language features. There are 48


keywords in c++. c++ contains
16 extra keywords

than c.

* Identifiers: Indentifiers refers to the names of variables, functions,


arrays, classes etc. created by the programmer.

* Basic datatypes:


(a) User defined [structure, union, class, enumeration]


(b) built
-
in
type [int, char, void, float, double]


(c) derived type [array, function, pointer]

* Operators:


::
-
> Scope resolution operator


::*
-
> pointor
-
to
-
member declaration


-
>*
-
> pointor
-
to
-
member operator


delete
-
> memory release

operator


endl
-
> line feed operator


new
-
> memory allocation operator


setw
-
> field width operator



C++ Keywords
:

16 extra keywords:


class


catch


delete


friend


inline


new


operator


private


protected


public


template


this


throw


try


virtual


asm


Default Arguments in C++
:

One of the most useful facilities available in C++ is the facility to define

default argument values for functions. In the function prototype declaration,

the defalut

values are given. Whenever a call is made to a function without

specifying an argument, the program will automatically asign values to the

parameters from the default function prototype declaration. Default arguments

facilitate easy developme
nt and mainte
nance of programs.

example:


float amount(float p,int t,float r=0.15); //declaring a fn with default value


r=0.15


value=amount(5000,7); //calling function with two arguments


Note: The default arguments mus
t be declared from right to left


Memory Management Operators in C++
:

c++ allows us two unary operators to allocate and deallocate memory. Those are

new and delete. Memory is allocated by
'new'
operator and deallocated by

'delete'

operator.

new

operator: The new operator is used to create a heap memory space for an

object of a class. C++ provides a new way in which dynamic memory is allocated.

In reality the new keyword calls upon the function operator new() to obtain

storage.


Basically, an a
llocation expression must carry out the following three

things:

* Find storage for the object to be created.

* Initialize that object, and

* Return a suitable pointer type to the object.

The new operator returns a pointer to the object created. Here,
pointers to

functions can be used for allocating memory.


syntax : datatype pointor
-
var = new datatype;

example : int *p;


float *q; (or) int *p=new int;


p=new int; float *q=new float;


q=new float;

I
f the call of new operator is successful, it returns a pointor to the space

that is allocated. Otherwise it returns Zero if the space could not be found

or if
some kind of error is detected.

delete operator: The delete operator is used to destroy the vari
able space

which has been created by using the new operator dynamically.

syntax: delete pointer;

example:

char *ptr_ch=new char;

int *ptr_i=new int;

delete ptr_ch;

delete ptr_i;

Note:the delete operator is used for only releasing the heap memory space

whi
ch was allocated by the new operator.


if statement in C++
:

if statement


The if statement is used to write conditional expressions. If the given

condition is true then it will execute the statements. Otherwise it will

execute optional statements.

syntax:

if<conditon>

{


-----


-----

}

example:

if(age==18)

{


cout<<"eligible to vote";

}

if
-
else statement in C++
:

if
-
else statement


In if
-
else statement, if the given condition is true then it will execute the

statements

otherwise it executes the else part statments.

syntax:

if<conditon>

{


-----


-----

}

else

{


-----


-----

}

example:

if(age==18)

{


cout<<"eligible to vote";

}

else

{


cout<"Not eligible to vote";

}

switch statement in C++
:

switch statement

The switch statement is a special multiway decision maker that tests whether

an expression matches one of the number of constants values and the braces

accordingly.

syntax:

switch(expression)

{


case constant_1:


{


-----


}


break;


case

constant_2:


{


-----


}


break;


case constant_n:


{


-----


}


break;


default:


statement;

}

example:

switch(ch)

{


case 'R':


cout<<"Red";


break;


case 'W':


cout<<"White";


break;


default:


cout<<"Wrong choice:";

}

for in C++

for loop

The for loop is most commonly used statement in c++. This loop consists of

three expressions. The first expression is used to initialize the index value,

the second to check whether or not the loop is to be continued again and the

third to change the index value for the further iteration.

syntax:

for(expression_1;expression_2;expression_3)


statements;

example:

sum=0;

for(i=0;i<=10;i++)


sum=sum+i;


while in C++

while loop

The while loop is used when we are not certain that the lo
op will be executed.

After checking the initial condition is true or false and finding it to be

true, only then the while loop will
enter into the loop operations.

syntax:

while(condition)

{


statements;

}

example:

sum=0;

i=0;

while(i<=100)

{


sum=sum+i
;


i++;

}

do
-
while in C++

do
-
while loop

Whenever one is certain about a test condition, then the do
-
while loop can be

used. As it enters into loop atleast once and checks whether the given

condition is true or false. As long as the test condition is tru
e, the loop

operations are repeated until the condition satisfied.

syntax:

do

{


statements;

}while(condition);

example:

sum=0;

i=0;

do

{


sum=sum+i;


i++;

}while(i<=100);


break statement in C++

break statement loop

The break statement is used to
terminate the control from the loop. The break

statement is normally used in switch
-
case structre and it can be used in other

loops also like for, while and do
-
while.

syntax:

break;

example1:

switch(day)

{


case 1: cout<<"Monday"; break;


--------


-
-------

}

example2:

i=0;

while(i<=10)

{


cout<"enter a number";


cin>>no;


if(value<=0)


cout<<"Zero or non
-
ve found";


break;

}

continue statement in C++

continue statement loop

The continue statement is used to repeat the same operations onc
e again even

it checks the error.

syntax:

continue;

example:

i=0;

while(i<=10)

{


cout<"enter a number";


cin>>no;


if(value<=0)


cout<<"Zero or non
-
ve found";


continue;

}

goto statement in C++

goto statement loop

The goto

statement is used to alter the program execution sequence by

transfering the control to some other part of the program.

syntax:

goto <name>

example:

goto xyz;

xyz: statements;


Arrays in C++

Arrays

An array is a collection of identical data objects which are stored in

consecutive memory locations under a com
mon heading or a variable name.

Array declaration:

storage_class
data type

array_name[expression]

Here, storage_class refers to the scope of the

array variable such as

external,static or an automatic.

data_type is used to declare the nature of the data elements stored in the

array like char,int,float

array_name

is the name of the array, and the
expression

is used to declare

the size of

the memor
y locations required.

Array initialization:

storage_class data_type array_name[expression]=


{element
-
1,element
-
2........element
-
n};

example:

int a[7]={1,2,3,4,5,6,7};

char name[5]={'c','n','c','p','p'}

Arrays and functions:

The entire array can

be passed on to a function in c++. An array name can be

used as an argument for the funciton declaration. No subscripts or square

brackets are required to invoke a function using arrays.

example:

void main()

{


int sumarray(int a[],int

n); //function declaration


----


----


sum=sumarray(a,n); //function calling

}

int sumarray(int a[],int n) //function definition

{


------


------

}


Multi dimensional arrays:

Multidimensional arrays are defined in the same manner

as one dimensional

arrays, except that a seperate pair of square brackets are required for each

subscript. Thus, a two dimesional array will require two pairs of square

brackets; a three dimensional array require three pairs of square brackets

and so o
n.

syntax:

storage_class data_type array_name[expression_1][expression_2]...[expression_n]

example:

int value[50][10][5];

float c[10][10];

char line[10][80];

static double r[100][100][10];

character array:

By using character array we can declare the
alphanumeric data.

syntax:

storage_class character_data_type array_name[expression];

example:

static char line[50];

Functions in C++

Function: A complex problem may be decomposed into a small or easily manageable

parts or modules called functions. Function
s are very useful to read, write,

debug and modify complex programs They can also be incorporated in the main

program. The main() itself is a function is invoking the other functions to

perfom various tasks.

Defining a function:

syntax:

functiontype func
tionname(datatype arg1,datatype arg2....)

{


------------


------------

}


calling function and called functions:

calling function:

The function which calls another function is known as calling

function.

called function:

The function which is call
ed is k
nown as called function.

Return statement:

The keyword return is used to terminate function and return a value to its

caller. The return statement may also be used to exit a function without

returning a value. The return statement may or may not include a
n expression.

syntax:

return;

return(expression);

Actual and formal arguments:

Actual arguments:

An actual argument is a variable or expression contained in

a function call.

formal arguments:

Formal arguments are the parameters present in a function
definition which may

also be called as dummy argumen
ts or the parametric variables.

Local and global variables:

local variables:

Local varibles are defined inside a function block or a

compound statement.

global variables:

Global variables are variables d
efined outside the main

function block. Whenever some of the variables are treated as constants both in

the main and the function block, it is adv
isable to use global variables.

Recursive function:

A function which calls itself directly or indirectly again

and again is known

as the recursive function.


Preprocessor:

Preprocessor is a program that modifies the c++ source program according to

directives supplied in the program. The original source program is usually

stored in a file. The preprocessor does n
ot modify this program file, but

creates a new file that contains the processed version of the program. This

new file is then submitted to the compiler. The preprocessor makes the program

easy to understand and port i
t from one platform to another.

The
preprocessor carries out the following actions on the source file before

it is presented to the compiler.

* replacement of defined identifiers by piecies of text.

* conditional selection of parts of the source file.

* inclusion of other files.

*
renumbering of source files and renam
ing of the source files itself.

Rules for defining preprocessor

* All preprocessor directives begin with the # sign.

* They must start in the first column and there can be no space between sign


and the directive.

* T
he preprocessor directive is not terminated by a ;

* Only one preprocessor directive can occur in a line.

Macros in c++

Macro:

A macro is simply a substitution stri
ng that is placed in a program.

example:

#define max 100

void main()

{


char name[max];



for(i=0;i<=max
-
1;i++)


-----------------


-----------------

}

which is internally replaced with the following program

void main()

{


char name[100];


for(i=0;i<=100
-
1;i++)


-----------------


-----------------

}

and

subsequently compiled. Each occurance of the identifier max as a token is

replaced with the string 100 that follows the identifier in the #define line.

Macros with parameters in c++

A more complex form of a macro definition declares the names of formal


p
arameters within par
enthersis, seperated by commas.

syntax:

#define

name(var1,var2.
......varn) substitution_string

example:

#define product(x,y) ((x)*(y))

#define max(x,y) ((x)>(y)?(x):(y))

#define min(x,y) ((x)<(y)?(x):(y))

Macros operate purely by textual substitution of tokens, The c++ compiler

parses the source program only after the completion of the macro expansion

processes are completed.

example:

#define product(x) (x)*(x)

void main()

{


product(10);


------


--
----

}

product(10) expands to 10*10 then it shows result accordingly.


Header Files in c++

Headerfiles:

A headerfile contains the definition, global variable declarations and

initialization by all file in a program. Header files are not compiled

seperately. The header file can be included in the program using macro

definition #include command. A header file can be declared as a first line

in any c++ program.

example:

The standard input/output(stdio.h> header file contains the macro definitions
and functions needed by the p
rogram
input/output statements.

The header file can be declared in one of the following ways


#include<iostrem.h>


(or)


#include "iostream.h"

Standard functions:

Standard libraries are used to perform some p
redefined operations on characters,

strings etc. The standard libraries are invoked using different names such as

library functions, built in functions or predefined functions. As the term

library function indicates, there are a great many of them actuall
y they are

not part of the language. Many facilities that are used in c++ programs need

not be part of c++ language.

Most of the c++ compilers support the following standard library facilities

* operations on characters

* operations on strings

* mathemati
cal operations

* storage allocation procedures

* input/output operations

Storage Classes in C++

Auto

Automatic variables are internal or local variables which are declared inside

a function. Internal variables are often refered to as automatic due the fact

that their memory space is automatically allocated as the function is entered

and released as soon as it leaves. Automatic variables given temporary memory

space. They have no meaning outside the function in which they are declared.

Auto variables can be
declared not only at the
beginning

of a function but also

at the
beginni
ng of a compound statement also.

External

Variables which are declared outside the main are called external variables and

these variables will have the same data type throughout the pr
ogram, both in

main and in the functions.

Static

Static variables are defined within a function and they have the same scope

rules of the automatic variables but in the case of static variables, the

contents of the variables will be r
etained throughout th
e program.

Register

Generally
variables

are stored in memory. As accessing a memory location takes

time(much more time than accessing one of the machine's registers), one can

make the computer to keep only a limited number of variables in their registers

f
or fast processing. Whenever some variables are to be read or repeatedly used,

they can be assigned as register
variables
.

Pointers

in C++

Pointers

A
pointer

is a variable which contains the address of memory location of

another variable. A
pointer

provides an indirect way of accessing the value of

a data item.

Pointer

Operators

pointer

operators:

1. address of(&) operator:


unary operator, returns the memory address of the operand.

2. value at address(*) operator:


unary operator, returns the v
alue co
ntained in the memory location.

Pointer

Arthematic:

We can perform the following
arithmetic

operators on
pointers

+ addition eg: *c=*a+*b;

-

subtraction eg: *c=*a
-
*b;

* multiplication eg: *c=*a**b;

/ division eg: *c=*a/*b;

% modulus eg: *c=*a%*b;

++ increment and

--

decremant

Note:

++operator causes the
pointer

to be incremented, but not by 1.

--
operator causes the
pointer

t
o be decremented, but not by 1.

Pointers

and one dimensional array:

example: int value[
20];


int *ptr;

Here, the
pointer

variable holds the address of first element in the value

array i.e address of value[0].means ptr=&value[0] (or) ptr=&value[]

Pointers

and two dimensional array

A
pointer

to an array contains the address of the

first
element. In

one

dimensional array, the first element is &a[0] but in the two dimensional

array the first element is &a[0][0]

example:

int a[][];

int *ptr;

ptr=a; /*the address of 0throw and the 0
th

row of the 2d array



a

is assigned to the ptr.

pointers

and funcitons:

Pointers

are very much used in a function declaration. Sometimes only with a

pointer

a complex function can be easily represented and accessed. The use of

the
pointers

in a function definition may classifie
d into two groups

*
call by value


*
callby
reference


pointers

and structures

A
pointer

can also be used to hold the address of a struct
ure variable. The

pointer

variable is very much used to
construct

complex
data structures

like

linked lists, double linked lists and binary trees etc.

example:

struct sample

{


int x;


float y;


char s;

};

struct sample *ptr;

where ptr is a pointor

variable holding the address of the structure sample and

is having three members such as int x, float y, char s. The pointor structure

variable can be accessed and processed by using 2 operators.

1. .(dot) operator :


(*structure_name).field_n
ame = variable;

2.
-
>(dash followed by greaterthan) :


structure_name
-
>field_name = variable;


Classes in c++

Class:

A class is a user defined data type which consits of two sections, a private

and

protected section that holds data and a public section that holds the

interface operations. A class declaration specifies the representation of

objects of the class, operations that can be applied to such objects.


Syntax:

class <userdefinedname>

{


p
rivate:


data_type members


implementation operations


list of friend functions


public:


data_type members


implementation operations


protected:


data_type operations


imp
lementation operations

};


class members can be one of the following member lists:

* data

* functions

* classes

* enumerations

* bitfields

* friends

* data type names


example:

class student

{


private:


long int rollno;


int age;


char sex;


float height,weight;


public: void getinfo();


void putinfo();

};


Defining the object of a class:

In general. a class is a user defined data type, while an

object is an instance of a class template. A class

provides

a template, which defines the member functions and variables

that are required for objects of the class type.

Syntax for defining object:

class <userdefinedname>

{


private:


//data


//methods


public:


//methods


protected:


//data

};

user_defined_name object1,object2,object3.........objectn;

where object1,object2,object3...are the identical class of

the user_defined_name


example:

class student

{


private:


long int rol
lno;


int age;


char gen;


float height,weight;


public: void getinfo();


void putinfo();

};

student s1,s2; //s1,s2 a
re two objects of student class

Accessing the member of a class:

A data or function memb
er of a class construct is accessed

using the .(period) operator

syntax:

object.data_member

object.member_function


example:

class student

{


public:


long int rollno;


int age;


char gen;


float
height,weight;


void putinfo();

};

void main(void)

{


class student s1;


s1.rollno=100;


s1.age=15; s1.gen='f';


s1.height=5.5f;


s1.weight=50.5;


s1.putinfo();

}

Objects in c++

Defining the object of a class:

In general. a class is a user

defined data type, while an object is an instance

of a class template. A class provides a template, which defines the member

functions and variables that are required

for objects of the class type.

Syntax for defining object:

class <userdefinedname>

{


private:


//data


//methods


public:


//methods


protected:


//data

};

user_defined_name object1,object2,object3.........objectn;

where object1,object2,object3...are the identical class of

the user_defined_nam
e


example:

class student

{


private:


long int rollno;


int age;


char gen;


float height,weight;


public: void getinfo();


void putinfo();

};

student s1,s2; //s1,s2 are two objects of stude
nt class

Accessing Members of Class

Accessing the member of a class:

A data or function member of a class construct is accessed using the .(period)

operator

syntax:

object.data_member

object.member_function


example:

class student

{


public:


long int rollno;


int age;


char gen;


float height,weight;


void putinfo();

};

void main(void)

{


class student s1;


s1.rollno=100;


s1.age=15; s1.gen='f';


s1.height=5.5f;


s1.weight=50.5;


s1
.putinfo();

}

Differences between structures and classes

Structures

1. By default, the members of a structure are public i.e structure variables


can be accessed by any function[data hiding not possible].

2. In structures we can declare only variables.

3. We can't inherit a st
ructure from another structure.

Classes

1. By default, the members are private i.e class variables can be accessed


by only class member functions [data hiding is possible].

2. In classes we can declare both data members and membe
r functions.

3. We can inherit a class from another class.

Access
Specifier:

Private:

A
data member

can only be accessed by the member function and friends

of that class. The private data member is n
ot accessible out of the class.

Protected:

Data members

c
an only be accessed by member functions and friends of

that class. Also, these functions can be accessed by the member functions

and friends derived from that class. It is n
ot accessible to outside world.

Public:

Data members

which are declared in public s
ection, can be accessed by

any function in the outside world. The public
implementation

operations are

also known as out of the class.

Member Functions

Member Function:

A function declared as a member(without the friend specifier) of a class is

called as
a member function. Member functions are mostly given the attributes

of public because they have to be called outside the class either in a program

or in a function.

Member functions

can be classified into 3 types

Manager functions: Manager functions are us
ed to perform initialization and

clean up the instance of the class objects.

eg: constr
uctors and destructor functions

Accessor functions: The accessor member functions are the constructor functions

that return information about object current state.

eg:
const member function

Implementer

functions: These are the functions that make modifications to the

data members. These functio
ns are
also called as mutators.



Member Functions syntax, example

Member Function:

A class contains not only data members also
a function which are called

methods, it must b
e defined before it is be used.

Example:

class sum

{


int x,y;


public: int sum()


{


return x+y;


}


int diff()


{


return x
-
y;



}

};

Here, the functions sum() and diff() are defined within the

class declaration.

Defining Member functions out of the class in C++

Defining the member function outside of the class:

In c++, it is permitted to declare the member functions
either inside the class

or outside the class declaration. A member function of a class is defined

outside the class declaration using ::(scope resolution operator)

Syntax of the member function of a class outside its scope:


return_type <classname> :
: me
mber_fn(arguments 1,2,...n)

Note:

1. The type of member function arguments must exactly match with the types


declared in the class

definition of the <class_name>

2. Only scope resolution operator identifies the function as a member of a


particular c
lass.

3. Without this scope operator, the function definition woulds create an


ordinary function, subject to the lusual function rules to access and


scope.


Example:

class sum

{


int x,y;


public: int sum(); //function declaration



int diff(); //function declaration

};

int sum :: sum() //function definition

{


return x+y;

}

int sum :: diff() //function definition

{


return x
-
y;

}

Array of class Objects

Array of class objects:

An array is a user defined datatype

whose members are homogeneous and stored

in contiguous memory locations. For designing large size of databases arrays

are very essential.

Syntax:

class user_define_name

{


private:


//data


//members


public :


//members


protected:


//data

};

class user_defined_name object[max];

where max is the user defined size

of the array of class objects.

example 1:

class student

{


int rno;


char name[20];


public: void getinfo();

}stuobj[100];//100
students


example 2:

const int max=200;

class employee

{


char name[20],ecode[20];


public: void getinfo();

};

class employee obj[max];

Pointors And Classes

Pointors and classes:

we can declare a pointer variable as a member to a class.

example:

class sample

{


int x;


float y;


char s;


public: void getdata();


void display();

};

sample *ptr;

where ptr is a pointer varibale that holds the address of the class object

sample and consists of the three data members such as int x, float

y, char s

and also holds member functions such as getdata() and display().


The pointer to an object of class variable will be accessed and processed in

one of the following ways

1. (*object_name).member_name=variable;

2. objec
t_name
-
> member_name
=variable;

example 1: example 2:

class student class student

{






{


//datamembers //datamembers


public: member_functions(); public: memb
er_functions();

};





};

void main(void) void main(void)

{ {


student *ptr; student *ptr;


............. ...
..........


............. .............


(*ptr).datamember; ptr
-
>datamember;


(*ptr).member_function(); ptr
-
>member_function();

}






}




Nested Classes

Nested classes:

c++ permits declaration of a class within another class. A class declared as a

member of another class is called as a nested class. The name of a nested class

is local to the enclosing class. The nested class is in the scope of its

enclosing class.

syntax:

class outer_class_name

{


//data


//member functions


class inner_class_name


{


//data of inner class


//member functions of inner class


}; //end of inner class

}; //end of outer class

outer_class_name object1;

outer_class_n
a
me :: inner_class_name object2;

example:

class student_info

{


char name[20],sex;


int rollno;


public: student_info(char *na,int rn,char sx);


void display();


class date


{


int day,month,year;


public: date(int

dy,int mh,int yr);


void show_date();


};//end of date class

};//end of student_info class

Constructor:

* A constructor is a special member function for automatic initialization of


an object.

* Whenever the object is created, the special member function i.e the


constructor
will be executed automatically.

* A constructor function is different from all other nonstatic member functions


in a class because it is used to initialize the variables

of whatever


instance being created.

Rules for writing constructors:

1. A constructor name must be the same as that of its class name.

2. It is declared with no return type not even void.

3. It cannot be declared as const or volatile.

4. It may not be st
atic.

5. It may not be virtual.

Syntax for writina a constructor:

class <cname>

{


//data


public: cname();

};

cname :: cname()

{


.....


.....

}


Default Constructor:

* The default constructor is a special member function which is invoked by c++


co
mpiler without any argumnet for initializing the objects of a class.

* In other words, a default constructor function initializes the data members


with no arguments.

* It may be explicitly written in a program, in case default constructor is


not

defined in a program, the c++ compiler automatically generates it in a


program.

Syntax:

class <cname>

{


//data


public: cname() //default constructor


{




}


......


......

};


(or)

class <cname>

{


//data


pub
lic: cname(); //default constructor


......


......

};

cname :: cname() (or) //defining outside of the class

cname :: cname(int =0) //means without any arguments

{

}

Parameterized Constructors in C++

Parametarized Constructor:

C++ allows
to achieve by passing arguments to the constructor function when the

objects are created. The construtor that can take arguments are called

Parametarized constructor.


Syntax:

class <cname>

{


//data


public: cname(arguments);


.........



.........

};


Examples:

class student

{


char name[20];


int rno;


public: student(char,int);


};

student :: student(char n,int r)

{


name=n;


rno=r;

}


Copy Constructor:

* Copy constructor are always used when the compiler has to create a


temporary object of a class object.

The copy constructors are used in the following situations


* The initialization of an object by another object of the same class.


* Return
of objects as a function value.


* stating the object as by value parameters of a function.


Syntax:

class_name :: class_name(class_name &ptr)


Example:

X :: X(X &ptr)

Here, X is userdefined class name and


ptr is pintor to a class object X.


* Nor
mally, the copy constructor take an object of their own class as arguments


and produce such an object.

* The copy constructors usually do not return a function value. Constructors


cannot return any function values.


Destructor:

* A destructor is a func
tion that automatically executes when an object is


destroyed.

* A destructor function gets executed whenever an instance of the class to


which it belongs goes out of existence.

* The primary usage of the destructor function is to release space on the
heap.

* A destructor function may be invoked explicitly.

Rules for writing destructor

1. A destructor function name is the same as that of the class it belongs


except that the first character of the name must be a tilde(~).

2. It is declared with no ret
urn types not even void since it cannot ever


return a value.

3. It cannot be declared static, const or volatile.

4. It takes no arguments and therefore cannot be overloaded.

5. It should have public access in the class declaration.


Syntax:

class <cname
>

{


//data


public: cname(); //constructor


~cname(); //destructor

};


Example:

class employee

{


char name[20],address[50];


int ecode;


public: employee(); //constructor


~employee(); //destructor

};




Inheritance
:

Inheritance is the most powerful feature of object oriented programming.

Inheritance is the process of creating new class from an existing class. The

existing class is known as base class and the newly created class is called as

a derived clas
s. The derived class inherits all capabilities of the base class.

It can also add some more features to this class. The base class is unchanged

by its process.

Advantages:

* Reusability of the code.

* To increase the reliablity of the code

* To add some
enhancements to the base class.

Inheritance

Any class can serve as a base class. A derived class may be defined as a base

of another class. A base class can be classified into two types


*
direct base class


*
indirect base class

Direct base class:

A base class is called a direct base if it is mentioned in the base list.

eg1:

class baseA

{


---------


---------

};

class derivedB : public baseA

{


---------


---------

};

Here, baseA is a direct base.

eg2:

class baseA

{


---------


---------

};

class baseB

{


---------


---------

};

class derivedB : public baseA,public base B

{


---------


---------

};

Here, baseA and baseB are direct base.

Indirect base class:

A derived class can itself serve as a base class subject to access control.

When a derived class is declared as a base of another class, the newly derived

class inher
its the properties of its base classes including its data members

and member functions. A class is called as an indirect base if it is not a

direct base, but is a base class of one of the classes mentioned in the base

list.

eg:

class baseA

{


--------


--------

};

class derivedB : public baseA

{


--------


--------

};

class derivedC : public derivedB

{


---------


---------

};

Here, class derivedB is a base of the class derivedC that is called as an

indirect base class.


Single inheritance is

the process of creating new classes from an exsiting base

class. The existing class is known as the direct base class and the newly

created class is called as a singly derived class.

Diagramatic Representation:



Syntax for derived class in Single
Inheritance

The general syntax for derived class declaration is

class derived_class_name : private/public/protected base_class_name

{


private:


//data members


public:


//data members


//methods


protected:


//data members

};


eg:

class basic_info

{


char name[20];


long int rollno;


char sex;


public:


//methods

};

class physical_fit : public basic_info

{


float ht,wt;


public:


//methods

};


The derived class
inherits

the properties of its base classes, including its

data member and member functions. The physical_fit is a derived class which has

two components
-

private and public. In addition to its new data members such as

height and weight, it may inherit the data me
mbers of the data members of the

base class. The derived class contains not only the methods of its own but also

its base classes.







Multilevel Inheritance

The multilevel inheritance is the process of creating a new class from already

derived class. H
ere the exsiting derived class is intermediate base class.

Newly created class is derived class.

Diagramatical representation:



Syntax for derived class in Multilevel Inheritance

The general syntax for mulilevel deriving is

class derived_class_name

: private/public/protected base_class_name

{


private:


//data members


public:


//data members


//methods


protected:


//data members

};

class derived_class_name1 : private/public/protected derived_class_name

{


privat
e:


//data members


public:


//data members


//methods


protected:


//data members

};





Multiple Inheritance

Multiple Inheritance

Multiple inheritance is the process of creating a new class from more than

one base classes.

Diagrametical Representation:



Syntax for derived class in Multiple Inheritance

The general syntax for multiple inheritance is

class baseA

{


-----


-----


-----

};

class baseB

{


-----


-----


-----

};

---

---

class basen

{


-----


-----


-----

};

class derivedC : public baseA, public baseB,
------
basen

{


-----


-----


-----

};








Hierarchical inheritance


Hierarchical inheritance is the process of deriving two or more classes from

only one base class.

Diagrametical

Representation:


Syntax For Deriving in Hierarchical Inheritance

The general syntax for hierarchical inheritance is

class baseA

{


-----


-----


-----

};

class derivedA : public baseA

{


-----


-----


-----

};

class derivedB

: public baseA

{


-----


-----


-----

};

class derivedC : public baseA

{


-----


-----


-----

};

Hybrid Inheritance

Hybrid Inheritance

Hybrid inheritance is the combination of types of inheritance.

Diagrametical Representation




Container
Class

C++ allows us to declare an object of a class as a member of another class.

When an object of a class is declared as a member of another class, it is

called as a container class.

The general syntax for container class declaration is

class c1

{


----
-


-----

};

class c2

{


-----


-----

};

class cn

{


-----


-----

};

class derived_class

{


c1 obj1; //object of the class1


c2 obj2; //object of the class2


-----


-----


cn obj2; //object of the classn

};


Overloading
definition
:

Overloading refers to the use of the sam
e thing for different purposes.


Advantages

* Saving memory

* Increases the performance

* Reduces
the complexity

Types

* Function Overloading

* Operator Overloading

Function Overloading

Function Overloading
definition:

Function overloading is a logical method of calling several functions with

different arguments and datatypes that perform basically identical things by

the same name.

Advantages
:

* Eliminating the use of different function names for the same o
perations.

* Helps to understand, debug and group easily.

* Easy maintainability of the code.

* Better understandability of the relationship b/w the program and the outside


world.


Function overloading is an easy concept in c++ and generally it is used

within the class concept for member functions and constructors. The compiler

classifies the overloaded function by its name and the number and type of

arguments in the function declaration. The function declaration and definition

is essential for each fu
nction with the same function name but with different

arguments and data types.

Examples:

void swap(int,int); //swaping two integer variables

void swap(float, float); //swpaing two floating variables

void swap(char,char); //swaping two characters

O
perator Overloading

Operator Overloading definiiton

Operator overloading is the exciting feature of c++. The main advantage of

using operator overloading in a program is that it is much easier to read

and debug.

syntax:

return_type :: operator
op(arguments)

{


function body

}

The keyword operator must be preceded by the return type of a function which

gives information to the compiler that overloading of operator is to be carried

out.

Rules for overloading operators:

1. Only those operators t
hat are predefined in the c++ compiler can be used.


Users can't create new operators such as $, @ etc.

2. Users can't change the operator templates. Each operator in c++ comes with


its own template which defines certain aspects of its use, such as
whether


it is a binary operator or a unary operator and its order of precedence.


This template is fixed and c
an't be altered by overloading.

3. Overloading an operator never gives a meaning which is radically different


from its natural meaning.

4
. Unary operators overloaded by means of a member function take no explicit


arguments and return no explicit values when they are overloaded by means


of a friend function, they take no reference argument, namely the name of


the relevant class.


Polymorphism in C++

Polymorphism is the one of the important features of object oriented

programming language. The word 'poly' is from a Greek word meaning many and

'morphism' from Greek word meaning form, and thus polymorphism means many

forms.



In Object oriented programming, polymorphism refers to identically name

methods that have different behaviour depending on the type of object they

refer.



Polymorphism is the process of defining a number of objects of different

classes into a
group and call the methods to carry out the operation of the

objects
using different function calls.


In other words, polymorphism means to carry out different processing steps

by functions having same messages. It treats objects of related classes in

a

generic manner.

EarlyBinding in C++


Choosing a function in normal way, during compilation time is called as

early binding or static binding or static linkage. During compoilation time,

the c++ compiler determines whch funciton is used based on the pa
ramenters

passed to the function or the functions's return type. The compiler then

substitutes the correct function for each invocation. Such compiler based

substitut
ions are called static linkage.


By default c++

follows early binding. With early binding, one can achieve

greater efficiency. Function calls are faster in this case because all the

information necessary to call the function is hardcoded.

LateBinding in C++


Choosing functions during execution time i
s called late binding or dynamic

linkage. Late binding requires some overhead but provides incresaed power

and flexibility. The late binding is implemented through virtual functions. An

obect of a class must be declared either as a pointor to a class or
a reference

to a class.

Polymorphism With Pointors

Pointors plays an important role in polymorphism. To enable polymorhism, C++

allows a pointor in a base class to point to either a base class object or to

any derived class object.

Example:

class baseA

{


------


------

};

class derivedD : public baseA

{


------


------

};

void main()

{


baseA obja;


derivedD objd;


baseA *ptr;


ptr=&obja; //Pointor to the same class


ptr=&objd; //pointor to the derived calss


----


----

}

By contra
st, a pointor to a derived class object may not point to a base class

object without explixit casting.

example:

void main()

{


baseA obja;


derived *ptr; //pointor of the derived class


ptr=(derived*) &obja;


-----


-----

}

Virtual functions:

Virtual functions are advanced features of object oriented programming language.

A virtual function is one that does not really exist but it appears real in

some parts of a program.


When we use the same function name in both the base and derived class
es,

the function in base class is declared as virtual. The function will be chosen

at the time of running.


To make a member function virtual, the keyword virtual is used in the

methods while it is declared in the class definition. The keyword virtual

should be preceded by a return type of the function name. The compiler gets

information from the keyword
virtual

that it is a virtual function and not a

con
ventional function declaration.

syntax:

class <class_name>

{


private:


-----


-----


public: virtual return_type fname1(arguments);


virtual return_type fname2(arguments);

};

Rules For Writing Virtual Functions

Rules:


The following are the rules
for declaring virtual functions

* The keyword virtual should not be repeated in the definition if the


definition occurs outside the class declaration. The use of a funcion


specifier virtual in the f
unciton declaration is invalid.

* A virtual function cannot be a static member becau
se a virtual member is


always a member of a particular object in a class rather than a member of the


class as a

whole.

* A virtual function can't have a constructor member function but it can have


the destructor member function.

* A destructor memb
er function does not take any argument and no return type


can be
specified for it not even void.

* It is an error to redefine a virtual method with a change of return data type


in the derived class with the same parameter types as those of a virtual


method in the base class.

* Only a member function of a class can be declared as virtual. It is an error


to declare a non member function of a class virtual.


Pure Virtual Functions in C++

Pure Virtual functions:

A pure virtual function is a t
ype of function which has only a function

declaration. It does not have the function definition.


(or)

The virtual fuction which is equated to zero if it does not have any function

definition i
s also a pure virtual function.

example:

c
lass base

{


-----


-----


public: virtual getdata();


virtual display();

};

class derivedB : public base

{


-----


-----

};

void base :: getdata() { }//pure virtual function def

void base :: display() { }//pure virtual function def

example1:

class base

{


-----


-----


public: virtual getdata()=0;


virtual display()=0;

};

class derivedB : public base

{


-----


-----

};

Abstract base classes:

A function which has only declaration but not the definition (or) The
function

declaration which is equated to zero is called a pure virtual function. A

class which consists of pure virtual functions is called an abstract base

class.


Function Templates

Template:

Template is a method for writing a single
function or class for a family of

similar functions or classes in a generic manner. When a single function is

written for a family of similar functions, it is called as a
'function

template'.

eg:

swap(char *,char *) //swapping two characters

{


}

swap(int
, int) //swapping two integer quantities

{


}

swap(float, float) //swapping two floating point nos

{


}

c++ provides certain features with the capability to define a single function

for a group of similar functions. When a single function is written for
a

family of similar functions, they are called function templates.

The main advantage of using function template is avoiding unnecessary reptition

of the source code. The object code becomes more compact and efficient than the

conventional way of declarin
g and de
fining the functions.

Secondly, full data type checking is carried out. The function template does

not specify the actual data types of the arguments that a function accepts but

it uses a generic or parameterized data type. In a function template

at least

one formal argument is generic.

syntax:

template<class T> T function_name(T formalarguments)

{


..........


..........


return(T);

}

where the template and class are keywords in c++ and the function template must

start

with template and the

T is a paramerized data type.

The above declaration of a function template may be written in the following

format also.

template <class T>

T function_name(T formal arguments)

{


...........


...........


return(T);

}


example1:

A function template is defined to find the sum of the given

array of elements such as int, float or double

template<class T>

T sum(T *array, int n)

{


T temp=0;


for(int i=0;i<=n
-
1;++i)


temp=temp+array[i];


return(temp);

}


example2:

A function template is defined to swap two given items of

different data like int, float or a character

template <class T>

T swap(T &first, T second)

{


T temp;


temp=first;


first=second;


second=temp;


return(0);

}

Class Templates

A clas
s template is a class definition that describes a family of related

classes. C++ offers the user the ability to create a class that contains one

or more types that are generic or parameterized.

Syntax:

template<class T>

class user_defined_name

{


privat
e:


.........


.........


public:


.........


.........

};

example:

template <class T>

class sample

{


private:


T value,value1,value2;


public:


void getdata();


void sum();

};

void main()

{


sample <int> obj1;


sample <float> obj2;

}

Exception Handling in c++
:

The exception handling is one of the excellent feature of c++. An exception is

an error or unexpected event. The exception handleris a set of codes that

executes when an exception occurs.


Exceptio
n handling in c++ provides a better method by which the caller of a

function can be informed that so
me error condition has occured.

Whenever a caller of a function finds an error, it is difficult to check or

trace those errors. In c++, those types of error

conditions are handled easily

using the following keywords.


try


catch


throw

Whenever a caller function detects an error without exception handling, it is

very difficult to handle it in a complex and big wsoftware. The pro
gram must be

developed with exception handling in such way that it determines the possible

errors the program might encounter then include codes to handle them.

General Example:

In the program which performs the input/output operation in file processing,
it

is essential to check whether a file has been opened successfully or not and

to display the appropriate error message i
f any unexpected events occurs.

Exception handling provides another way to transfer control and information

from a point in the exe
cution of a program to an exception handler. A handler

will be invoked only by a throw expression in a code executed in the handler's

try block or the function calle
d from the handler's try block.

Normally, the exception handler consists of three blocks.



try block


handler


throw expression

Syntax:

try(expression)


catch(exception detector)


{


-------


-------


}

throw(expression)

{


-----------


-----------


//error message

}


A try block is a statement. A throw
expression is a unary expression of type

void.

Manipulator:

Manipulator functions are special stream functions that change certain

characteristics of the input and output. They change the format flags and

values

for a stream. The main advantage of using manipulator functions is that

they facilitate the formati
ng of input and output streams.


The following are the list of standard manipulators used in a c++ program.

To carry out the operations of these manipulato
r functions in a user program,

the header file input and output manipulator <iomanip.h> must be included.



endl




hex, dec, oct




setbase




setw




setfill




setprecision




ends




ws




flush




setiosflags




resetiosflags