UNIT – 1 : DATA ABSTRACTION AND OVERLOADING Overview of C++ – Structures – Class Scope and Accessing Class Members – Reference Variables – Initialization – Constructors – Destructors – Member Functions and Classes – Friend Function – Dynamic Memory Allocation – Static Class Members – Container Classes and Integrators – Proxy Classes – Overloading : Function overloading and Operator Overloading. 1.1 OVERVIEW OF C++ OOP as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. 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 closely to the functions that operate on it and protects it from accidental modification from outside junctions. It allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The data of an object can be accessed only the functions associated with the object. C++ is a general purpose programming language. The C++ language inherits a lot of C language syntax. That’s why people who know C Programming language can easily learn C++. This content is written for people who want to learn C++ Programming Language absolutely from scratch. In this content you will find useful information about the following C++ topics. Features
Emphasis is on data rather than procedure. Improvement over the structured programming paradigm. Data structures are designed such that they characterize the object. Functions that operate on the data of an object are tied together in the data structure. Data is hidden that cannot be accessed by external functions. Object may communicate with each other through functions. New data and functions can be added easily. Follow bottom up approach in program design.
1.1.1 BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING The object oriented programming approach is based on certain concepts that overcome the drawbacks of conventional programming approaches . These include Objects Classes Abstraction
Objects Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member functions to perform tasks. Class It is similar to structures in C language. Class can also be defined as user defined data type but it also contains functions in it. So, class is basically a blueprint for object. It declare & defines what data variables the object will have and what operations can be performed on the class's object. Abstraction Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes provide methods to the outside world to access & use the data variables, but the variables are hidden from direct access. This can be done access specifiers. Encapsulation It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class. Inheritance Inheritance is a way to reuse once written code again and again. The class which is inherited is called base calls & the class which inherits is called derived class. So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable. Polymorphism This is a way to use the same interface for the different data types. In simple words it can be described as using the same name for member functions that have different arguments. Polymorphism is not only related to member functions. It's discussed in more details in "C++ Polymorphism" Dynamic binding
Visit : www.EasyEngineeering.net
3 Visit : www.EasyEngineeering.net
Dynamic binding is determining the method to invoke at runtime instead of at compile time. Dynamic binding is also referred to as late binding. Message passing Message passing is a form of communication between objects, processes or other resources used in object-oriented programming, inter-process communication and parallel computing. 1.1.2. BENEFITS OF OOPS Through inheritance, we can eliminate redundant code and extend the use of existing classes which is not possible in procedure oriented approach. We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch which happens procedure oriented approach. This leads to saving of development time and higher productivity. The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. It is possible to have multiple instances of object to co-exist without any interference. It is possible to map objects 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 details of a model in implementable from. Object oriented systems can be easily upgraded from small to large systems. Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler. Software complexity can be easily managed. 1.1.3. DEMERITS OF OOPS With OOP, classes tend to be overly generalized. One need to do proper planning and proper design for OOPs. The program with OOP, programmer need proper skills such as design skills, programming skills , thinking in terms of objects, etc. 1.1.4. OBJECT ORIENTED LANGUAGES This can be classified into two categories : (1)Object based programming languages This type of language support the following features Data encapsulation Data hiding and access mechanisms
Visit : www.EasyEngineeering.net
4 Visit : www.EasyEngineeering.net
Automatic initialization and clear up objects Operator overloading Example : Ada programming (2)Object oriented programming languages Object oriented programming supports all of object programming features along with two additional features namely inheritance and dynamic binding Example : C++,Java etc 1.1.5. Features of C++ C++ is object oriented programming language and it is a very simple and easy language, this language have following features.
Simple Portability Powerful Platform dependent Object oriented oriented Case sensitive Compiler based
Visit : www.EasyEngineeering.net
5 Visit : www.EasyEngineeering.net
Syntax based language Use of Pointers 1.1.6. TOKENS The smallest individual unit is a program is known as a token. A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: identifiers, keywords, literals, operators, punctuators, and other separators. A stream of these tokens makes up a translation unit. C++ has the following tokens. Keywords
Keywords are the words that convey a special meaning to the language compiler. These are reserved for special purpose. It must not be used as normal identifier names. Many of the keywords are common to both C and C++ C++ have additional keywords to enhance its feature and make it an object oriented languages.
Identifiers Identifier refers to the name of the variables, functions arrays, classes etc. Created by the programmer. They are the fundamental requirement of any language. Each language has its own rules for naming identifiers.
Visit : www.EasyEngineeering.net
6 Visit : www.EasyEngineeering.net
Constants Constants or literals are data item that never change their value during the execution of a program. C++ allows several kinds of literals.
Integer constant Character constant Floating constant String literal
Strings C++ supports two types of string representation. C style character string String class type Operators 1.1.7. OPERATORS Operators are special type of functions, that takes one or more arguments and produces a new value. For example : addition (+), substraction (-), multiplication (*) etc, are all operators. Operators are used to perform various operations on variables and constants. Unary operators are those operators that require one operator to operate upon.
Assignment Operator ( = ) Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy it into the left-hand side (called lvalue). Assignment operator is the only operator which can be overloaded but cannot be inherited.
Mathematical Operators There are operators used to perform basic mathematical operations. Addition (+) , subtraction (-) , diversion (/) multiplication (*) and modulus (%) are the basic mathematical operators. Modulus operator cannot be used with floating-point numbers. C++ and C also use a shorthand notation to perform an operation and assignment at same type. Example, int x=10; x += 4 // will add 4 to 10, and hence assign 14 to X. x -= 5 // will subtract 5 from 10 and assign 5 to x.
Relational Operators These operators establish a relationship between operands. The relational operators are : less than (<) , grater thatn (>) , less than or equal to (<=), greater than equal to (>=), equivalent (==) and not equivalent (!=). You must notice that assignment operator is (=) and there is a relational operator, for equivalent (==). These two are different from each other, the assignment operator assigns the value to any variable, whereas equivalent operator is used to compare values, like in if-else conditions, Example int x = 10; //assignment operator
Visit : www.EasyEngineeering.net
8 Visit : www.EasyEngineeering.net
x=5; // again assignment operator if(x == 5) // here we have used equivalent relational operator, for comparison { cout <<"Successfully compared"; }
Logical Operators The logical operators are AND (&&) and OR (||). They are used to combine two different expressions together. If two statement are connected using AND operator, the validity of both statements will be considered, but if they are connected using OR operator, then either one of them must be valid. These operators are mostly used in loops (especially while loop) and in Decision making. Bitwise Operators There are used to change individual bits into a number. They work with only integral data types like char, int and long and not with floating point values.
Bitwise AND operators & Bitwise OR operator | And bitwise XOR operator ^ And, bitwise NOT operator ~
They can be used as shorthand notation too, & = , |= , ^= , ~= etc. Shift Operators Shift Operators are used to shift Bits of any variable. It is of three types, 1. Left Shift Operator << 2. Right Shift Operator >> 3. Unsigned Right Shift Operator >>> Unary Operators These are the operators which work on only one operand. There are many unary operators, but increment ++ and decrement -- operators are most used. Other Unary Operators : address of &, dereference *, new and delete, bitwise not ~, logical not !, unary minus - and unary plus +.
Visit : www.EasyEngineeering.net
9 Visit : www.EasyEngineeering.net
Ternary Operator The ternary if-else ? : is an operator which has three operands. int a = 10; a > 5 ? cout << "true" : cout << "false"
Comma Operator This is used to separate variable names and to separate expressions. In case of expressions, the value of last expression is produced and used. Example : int a,b,c; // variables declaration using comma operator a=b++, c++; // a = c++ will be done.
sizeof operator in C++ sizeOf is also an operator not a function, it is used to get information about the amount of memory allocated for data types & Objects. It can be used to get size of user defined data types too. sizeOf operator can be used with and without parentheses. If you apply it to a variable you can use it without parentheses. cout << sizeOf(double); int x = 2; int i = sizeOf x;
typedef Operator typedef is a keyword used in C language to assign alternative names to existing types. Its mostly used with user defined data types, when names of data types get slightly complicated. Following is the general syntax for using typedef, typedef existing_name alias_name
Lets take an example and see how typedef actually works. typedef unsigned long ulong;
Visit : www.EasyEngineeering.net
10 Visit : www.EasyEngineeering.net
The above statement define a term ulong for an unsigned long type. Now this ulong identifier can be used to define unsigned long type variables. ulong i, j;
1.1.8. STRUCTURE OF C++ PROGRAM C++ Programming language is most popular language after C Programming language. C++ is first Object oriented programming language. We have summarize structure of C++ Program in the following Picture –
Structure of a C++ Program Section 1 : Header File Declaration Section 1. 2. 3. 4.
Header files used in the program are listed here. Header File provides Prototype declaration for different library functions. We can also include user define header file. Basically all preprocessor directives are written in this section.
Visit : www.EasyEngineeering.net
11 Visit : www.EasyEngineeering.net
Section 2 : Global Declaration Section 1. Global Variables are declared here. 2. Global Declaration may include Declaring Structure Declaring Class Declaring Variable Section 3 : Class Declaration Section 1. Actually this section can be considered as sub section for the global declaration section. 2. Class declaration and all methods of that class are defined here. Section 4 : Main Function 1. Each and every C++ program always starts with main function. 2. This is entry point for all the function. Each and every method is called indirectly through main. 3. We can create class objects in the main. 4. Operating system call this function automatically. Section 5 : Method Definition Section 1. This is optional section . Generally this method was used in C Programming. Sample Program #include class person { char name[30]; int age; public : void getdata( ); void display( ); };
Visit : www.EasyEngineeering.net
12 Visit : www.EasyEngineeering.net
void person ::getdata( ) { cout<< “enter name :”; cin>>name; cout<<”enter age :”; cin>> age; } void person :: display( ) { cout<< “\n name :”<
Visit : www.EasyEngineeering.net
13 Visit : www.EasyEngineeering.net
1.1.9. CONCEPT OF DATATYPES The data types are used to create variables or your new data types. A variable is a amount of memory that has its own name and value. That's why it is important to know the built in data types, their properties and size. Definition : Data types are means to identify the type of data and associated operations of handling it.
C++ Data Types Type Name Int unsigned int bool char signed char unsigned char short
Bytes 4 4 1 1 1 1 2
Range of Values 2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 false or true 128 to 127 128 to 127 0 to 255 32,768 to 32,767
Visit : www.EasyEngineeering.net
14 Visit : www.EasyEngineeering.net
unsigned short Long unsigned long long long unsigned long long float double long double wchar_t
2 4 4 8 8 4 8 same as double 2
0 to 65,535 2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615 3.4E +/- 38 (7 digits) 1.7E +/- 308 (15 digits) Same as double 0 to 65,535
1.2. STRUCTURES Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collection of data of different data types. For example: You want to store some information about a person: his/her name, age and salary The struct keyword defines a structure type followed by an identifier (name of the structure). Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example: struct Person { char name[50]; int age; float salary; };
1.2.1. UNION A union is a user-defined type in which all members share the same memory location. This means that at any given time a union can contain no more than one object from its list of members. It also means that no matter how many members a union has, it always uses only enough memory to store the largest member. Unions in C++ is a user defined data type that uses the same memory as other objects from a list of objects. At an instance it contains only a single object.
Visit : www.EasyEngineeering.net
15 Visit : www.EasyEngineeering.net
Syntax: union union-type-name{ type member-name; type member-name; }union-variables; 1.2.2. Enumerated Data Type An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used. enum season { spring, summer, autumn, winter }; Here, the name of the enumeration is season. And, spring, summer and winter are values of type season. By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if necessary). enum season { spring = 0, summer = 4, autumn = 8, winter = 12 }; 1.2.3. Derived Data Types Array : Array is a collection of similar Objects We can have array of Integers, Characters, Strings, any user defined types, etc. Since we can have any kind of collection (Integers, Characters, Strings, etc.) in an array, so in a generic way we can call array is a collection of similar objects. Arrays are fixed in size After declaring an array, we cannot change the size of the array. That means we can't reduce the size nor increase the size of an array. Elements of an array will be allocated contiguously in memory When we create an array then each element of an array will be allocated in contiguous memory locations. Contiguous memory locations means that just after the first element of an array,
Visit : www.EasyEngineeering.net
16 Visit : www.EasyEngineeering.net
second element will be present in the memory. And just after the second element, third element will be present, and so on. The first element of an array will have the lowest address and the last element will have the highest address. Elements of an array are accessed by an index Elements of an array are accessed by an index. The first element will have the index 0, second element will have the index 1, third will have the index 2 and so on. The last element will have index (n-1) where n is the number of elements in an array. Example : float a[3]; // declares array of 3 floats a[0], a[1], a[2] Int b[2] [4]; // declares a 2 dimensional array of integers. b[0][0], b[0][1], b[0][2], b[0][3], b[1][0], b[1][1], b[1][2], b[1][3], Functions in C++ Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc. Syntax of Function return-type function-name (parameters) { // function-body } return-type : suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void. Function Name : is the name of the function, using the function name it is called. Parameters : are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list. void sum(int x, int y) { int z; z = x + y; cout << z; } int main() {
Visit : www.EasyEngineeering.net
17 Visit : www.EasyEngineeering.net
int a = 10; int b = 20; sum (a, b); } Here, a and b are sent as arguments, and x and y are parameters which will hold values of a and b to perform required operation inside function . Function body : is the part where the code statements are written. Declaring, Defining and Calling Function
Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Lets understand this with help of an example. #include < iostream.h> int sum (int x, int y); //declaring function int main() { int a = 10; int b = 20; int c = sum (a, b); //calling function cout << c; } int sum (int x, int y) //defining function { return (x + y); } Here, initially the function is declared, without body. Then inside main() function it is called, as the function returns sumation of two values, hence z is there to store the value of sum. Then, at last, function is defined, where the body of function is mentioned. We can also, declare & define the function together, but then it should be done before it is called. Pointers A pointer is a variable that holds a memory address This address is usually the location of another variable in memory. Pointers are used in C++ program to access the memory and manipulate the address.
Visit : www.EasyEngineeering.net
18 Visit : www.EasyEngineeering.net
Address in C++ To understand pointers, you should first know how data is stored on the computer. Each variable you create in your program is assigned a location in the computer's memory. The value the variable stores is actually stored in the location assigned. To know where the data is stored, C++ has an & operator. The & (reference) operator gives you the address occupied by a variable. If var is a variable then, &var gives the address of that variable. Example 1: Address in C++ #include int main() { int var1 = 3; int var2 = 24; int var3 = 17; cout << &var1 << endl; cout << &var2 << endl; cout << &var3 << endl; } Output 0x7fff5fbff8ac 0x7fff5fbff8a8 0x7fff5fbff8a4
References A reference is an alternative name for an object. A reference variable provides an alias for a previously defined variable. A reference declaration consists of a base type an & , a reference variable name equated to a variable name. The general form of declaring a reference variable is type & ref_var = var_name Where , type is any valid C++ data type. ref_var is name of reference variable.
Visit : www.EasyEngineeering.net
19 Visit : www.EasyEngineeering.net
Example : int total; int &sum = total; total=100; Sum is declared as a reference variable for a variable total. 1.2.4. SYMBOLIC CONSTANTS There are two ways of creating symbolic constant in C++. 1.Using the qualifier constant. 2.Defining a set of integer constant using enum keyword. 1. Using the Qualifier Const Any value declared as constant cannot be modified by the program. Const can be used in a constant expresson, such as const int size=10; char name[size]; Using Enumeration Naming integer constants is by enumeration. i.e., enum{x,y,z}; This defines x,y,z as integer constants with values 0,1,2 respectively. This is equivalent to const x=0; const y=1; const z=2; 1.2.5. DECLARATION OV VARIABLES All variables must be declared before they are used in executable statements. It allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. It also makes the program easier to understand because the variables are declared in the context of their use.
Visit : www.EasyEngineeering.net
20 Visit : www.EasyEngineeering.net
The declaration of a variable generally takes the following format: type name; where type is any C++ data type; name is the name of the variable Example :
signed int value; unsigned short count;
When more than one identifier of a type is being defined, a comma separated int of identifiers may follow the type specifier. Example : double salary, wage; Sample Program int main() { float x; float sum=0; for(int i=1;i<5;i++) { cin>>x; sum=sum+x; } float average; average=sum/(i-1); cout<
Visit : www.EasyEngineeering.net
21 Visit : www.EasyEngineeering.net
Initial value mane be specified in the definition of a variable. Example : int val=1001; double price=314.70, discount =0.22; Dynamic initialization One additional feature of C++ is that it permits initialization of the variables at run time. This is referred to as dynamic initialization. A variable can be initialized at run time using expressions at the place of declaration. float avg; avg=sum/count; then the above two statements can be combined into one as follows: float avg = sum / count; It will initialize avg using the information available at run time. i.e., using the values of sum and count known at run time. Reference Variables A reference variable provides an alias for a previously designed variable. A reference variable is created as follows. data type of reference_name=variable name Example : float total=100; float &sum=total; 1.2.6. OPERATORS IN C++ C++ Operators Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. C++ supports all operators of C, C++ introduces some new operators given as below: Symbols Name << Insertion operator.
1.2.7. EXPRESSIONS An expression is a combination of operators, constants and variables arranged as per the rules of the language. There are different categories of an expression are discussed here. Constant expressions: The expressions that comprise only constant values are called constant expressions. Some examples of constant expressions are 20, ‘ a‘ and 2/5+30 . Integral expressions: The expressions that produce an integer value as output after performing all types of conversions are called integral expressions. For example, x, 6*xy and 10 +int (5.0) are integral expressions. Here, x and y are variables of type int. Float expressions: The expressions that produce floating-point value as output after performing all types of conversions are called float expressions. For example, 9.25, x-y and 9+ float (7) are float expressions. Here, x 'and y are variables of type float. Relational or Boolean expressions: The expressions that produce a bool type value, that is, either true or false are called relational or Boolean expressions. For example, x + y<100, m + n==a-b and a>=b + c .are relational expressions. Logical expressions: The expressions that produce a bool type value after combining two or more relational expressions are called logical expressions. For example, x==5 &&m==5 and y>x I I m<=n are logical expressions. Bitwise expressions: The expressions which manipulate data at bit level are called bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions. Pointer expressions: The expressions that give address values as output are called pointer expressions. For example, &x, ptr and -ptr are pointer expressions. Here, x is a variable of any type and ptr is a pointer. Special assignment expressions: An expression can be categorized further depending upon the way the values are assigned to the variables. Chained assignment: Chained assignment is an assignment expression in which the same value is assigned to more than one variable, using a single statement. For example, consider these statements. a = (b=20); or a=b=20;
Visit : www.EasyEngineeering.net
23 Visit : www.EasyEngineeering.net
In these statements, value 20 is assigned to variable b and then to variable a. Note that variables cannot be initialized at the time of declaration using chained assignment. For example, consider these statements. int a=b=30; // illegal int a=30, int b=30; //valid Embedded assignment: Embedded assignment is an assignment expression, which is enclosed within another assignment expression. For example, consider this statement a=20+(b=30); //equivalent to b=30; a=20+30;
1.2.8. CONTROL STRUCTURES In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration. Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. C++ handles decision-making by supporting the following statements
if statement switch statement conditional operator statement goto statement
Decision making with if statement The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are, 1. 2. 3. 4.
Simple if statement If....else statement Nested if....else statement else if statement
Simple if statement The general form of a simple if statement is, if( expression ) {
Visit : www.EasyEngineeering.net
24 Visit : www.EasyEngineeering.net
statement-inside; } statement-outside; If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' is executed. Example : #include< iostream.h> int main( ) { int x,y; x=15; y=13; if (x > y ) { cout << "x is greater than y"; } }
if...else statement The general form of a simple if...else statement is, if( expression ) { statement-block1; } else { statement-block2; } If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and 'statement-block2' is executed. Example : void main( ) { int x,y; x=15; y=18;
Visit : www.EasyEngineeering.net
25 Visit : www.EasyEngineeering.net
if (x > y ) { cout << "x is greater than y"; } else { cout << "y is greater than x"; } }
Nested if....else statement The general form of a nested if...else statement is, if( expression ) { if( expression1 ) { statement-block1; } else { statement-block2; } } else { statement-block3; } if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is executed otherwise 'statement-block2' is executed. Example : void main( ) { int a,b,c; clrscr(); cout << "enter 3 number"; cin >> a >> b >> c; if(a > b) {
Visit : www.EasyEngineeering.net
26 Visit : www.EasyEngineeering.net
if( a > c) { cout << "a is greatest"; } else { cout << "c is greatest"; } } else { if( b> c) { cout << "b is greatest"; } else { printf("c is greatest"); } } getch(); }
else-if ladder The general form of else-if ladder is, if(expression 1) { statement-block1; } else if(expression 2) { statement-block2; } else if(expression 3 ) { statement-block3; } else default-statement; The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the statement associated with it is executed.
Visit : www.EasyEngineeering.net
27 Visit : www.EasyEngineeering.net
Example : void main( ) { int a; cout << "enter a number"; cin >> a; if( a%5==0 && a%8==0) { cout << "divisible by both 5 and 8"; } else if( a%8==0 ) { cout << "divisible by 8"; } else if(a%5==0) { cout << "divisible by 5"; } else { cout << "divisible by none"; } getch(); }
Looping in C++ In any programming language, loops are used to execute a set of statements repeatedly until a particular condition is satisfied
Visit : www.EasyEngineeering.net
28 Visit : www.EasyEngineeering.net
A sequence of statement is executed until a specified condition is true. This sequence of statement to be executed is kept inside the curly braces { } known as loop body. After every execution of loop body, condition is checked, and if it is found to be true the loop body is executed again. When condition check comes out to be false, the loop body will not be executed.
There are 3 type of loops in C++ language 1. while loop 2. for loop 3. do-while loop
while loop while loop can be address as an entry control loop. It is completed in 3 steps.
Variable initialization.( e.g int x=0; ) condition( e.g while( x<=10) ) Variable increment or decrement ( x++ or x-- or x=x+2 )
Visit : www.EasyEngineeering.net
29 Visit : www.EasyEngineeering.net
Syntax : variable initialization ; while (condition) { statements ; variable increment or decrement ; }
for loop for loop is used to execute a set of statement repeatedly until a particular condition is satisfied. we can say it an open ended loop. General format is, for(initialization; condition ; increment/decrement) { statement-block; } In for loop we have exactly two semicolons, one after initialization and second after condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. for loop can have only one condition.
Nested for loop We can also have nested for loop, i.e one for loop inside another for loop. Basic syntax is, for(initialization; condition; increment/decrement) { for(initialization; condition; increment/decrement) { statement ; } }
do while loop In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. General format of dowhile loop is,
Visit : www.EasyEngineeering.net
30 Visit : www.EasyEngineeering.net
do { .... ..... } while(condition);
Jumping out of loop Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becocmes true, that is jump out of loop. C language allows jumping from one statement to another within a loop as well as jumping out of the loop. 1) break statement When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. 2) continue statement It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle. Switch Statement This is alternate to the cascaded if (if-else ladder). This switch statement causes a particular group of statement to be chosen from several available groups. The selection is based upon the current value of variable or expression, which is included within the switch statement. Nested switch is also possible. If the expression or variable is of numeric type, the constant value need not be enclosed in either single quotation or double quotation mark. If variable or expression is of character type, the constant value should be enclosed in single quotation mark ( ’ ). If no case matching for corresponding value of the variable, default option will get executed. SYNTAX:
Example: … int a, b, c; char opt, action[20]; cout << “iput a and b?” ; cin >> a >> b; cout << “your option(+, –, *)?”; opt = getchar(); switch(opt) { case ‘+’ : c = a + b; strcpy(action, “sum”); break; case ‘ – ’ : c = a – b; strcpy(action, “difference”); break; case ‘ * ’ : c = a – b; strcpy(action, “product”); break; default: strcpy(action, “invalid action”); } cout << action << “of the “<< a <<” and b is =” << c << endl; …
This statement just alternate to the “simple if”. The only major difference between “simple if” and “ternary operator” is that we cannot use “if statement inside printf() function, but we can use ternary operator inside printf() function. SYNTAX:Exp1 ? Exp2 : Exp3; If Exp1 is evaluated to true than Exp2 is executed; otherwise Exp3 will be executed. Example: int x = 10, y = 20; cout << “The big number was” << (x > y ? x : y) << endl; 1.3. CLASS SCOPE AND ACCESSING CLASS MEMBERS CLASS SCOPE
Two principal form of scope: local scope and file scope. The basic rule for scoping is that identifiers are accessible only within the block in which they were declared. Local scope - local scope is scoped to block. Function bodies are example of blocks; they contain set declarations that includes their parameter. File scope has name that are external.
STORAGE CLASS
Storage classes are used to determine the life time(existence) and accessibility of variable during the program execution. There are four different storage-class specifications in C: automatic, external, static and register. They are identified by the keywords auto, extern, static and register, respectively. The general syntax for storage class specification are: Storage-specifiers data-type variable-name; (or) [Storage-specifiers] data-type variable-name-1 [,variable-name-2…]; Storage class associated with a variable can sometime be established by the location of the variable declaration with in the program. Variables which are declared inside function are automatically treated as auto variable and can be referenced only within the function in which it is declared. Similarly, variable declared outside of all function are automatically treated as external / global variables. Code fragment shown below describe several typical variable declarations. auto int a, b, c; extern float root1, root2; static int count; register int a, b;
Visit : www.EasyEngineeering.net
33 Visit : www.EasyEngineeering.net
AUTOMATIC VARIABLE (auto) Variables declared inside the functions are auto / local variables; they are accessible only with the function in which they are declared. They are created, the moment the function is called, and destroyed the moment function is exited. Automatic variable defined in different function independent of one another, even though they have the same name. Formal argument declared in the function is also treated as auto variable. It is not necessary to mention auto keyword explicitly in front of variable declaration. An automatic variable does not retain its value once control is transferred out of its defining function. Therefore, any value assigned an automatic variable within the function will be lost once the function is exited.
{ /* auto variable declaration */ int x, y, sum; float avg; auto char name[30]; ….. } EXTERNAL / GLOBAL VARIABLE (extern) Variables declared outside of all function are external / global variable. It is not required to mention extern keyword explicitly. An external variable can be assigned a value within one function, and this value can be used within another function. For an external variable definition, there is no extern keyword required. But for external variable declaration, extern keyword has to be explicitly specified. For external variable declaration memory will not be allocated. If the function definition precedes the external variable definition, then the function must include a declaration for the external variable. The name and its data type present in the declaration must match with the corresponding external variable definition that appears outside of the function. Example: void readX( ) { extern int x; // external variable declaration cout << “x?”; cin >> x; } int x; // external variable definition main( ) {
Visit : www.EasyEngineeering.net
34 Visit : www.EasyEngineeering.net
readX( ); cout << “X=” << x << endl; x += 10; cout << “X =% d” << x << endl; } STATIC VARIABLES Static variables are permanent variables within their own function or file. Unlike global variables they are not known outside the function or file, but they maintain their values between function calls. Either local variable or external variable can be qualified with static keyword. Based on that there are two types of static variable exist. They are local static and global static. STATIC LOCAL VARIABLES If the variable defined with in the function is qualified with static, it is called local static variable. Local Static variables are created, when you call the function first time and retain its values throughout the program life cycle, but accessible only with in the function in which it is defined. Similar to local variable outside the function it is not accessible. When function is called, its local variables are created, and upon its exit they are destroyed. So that local variable cannot retain their value between calls. But local static variable are capable of retain its value between function call. Example:
#include #include long int fibo() { static long int f1 = – 1, f2 = 1; long int f; f = f1 + f2; f1 = f2; f2 = f; return f; } main() { int cnt, n; clrscr(); cout << "How many fibonacci do you need to print: "; cin >> n; for(cnt = 1; cnt <= n; cnt++)
Visit : www.EasyEngineeering.net
35 Visit : www.EasyEngineeering.net
cout << “\t” << fibo(); getch(); }
Output How many fibonacci do you need to print 0 1 1 2 3 5 8
Suppose if variable f1, f2 is not declared as static variable, it does not retain its old value assigned in the previous function call. So that every time f1 and f2 will be initialized to –1 and 1, so that output will always zero, because f1 and f2 will be treated as auto variable. GLOBAL STATIC VARIABLES If an external variable or global variable is qualified with static, they are called global static variables. Static global variable is accessible and known only from different functions with in the same file in which it is defined, but from outside of file, it is not accessible. It has life time through out the program. Global variables are accessible not only accessible within the file in which it is declared, but outside of file also it is accessible. Example: static int x; // static global variable x cannot be accessible outside file void main () { read (); cout << “x = ” << x; } void read () { cout << “ x? ”; } cin >> x; REGISTER VARIABLE Only local/auto variable of type int, char, int*, char* can be declared as register variable. The register specifies request the compiler to keep the values of a variable in the registry of the CPU rather than in main memory, where normal variables are stored. Operation on a register variable could occur much faster than on a normal variable because the register variable was actually held in the CPU & did not require memory access time to determine or modify its value. Larger objects like’s arrays obviously cannot be stored in a register, since it will take more register area. Global Register variable are not allowed to declared as register variable.
Visit : www.EasyEngineeering.net
36 Visit : www.EasyEngineeering.net
Example:register int count; register char choice;
Function :
A problem in C++ can be decomposed into subprograms, each of which can be coded directly or further decomposed. This is the method of stepwise refinement. The function is used to write code for these directly solvable sub problems. These functions are combined into other functions, and ultimately used in main( ) to solve the original problem. FUNCTION DEFINITION The general form of function definition is: return-type function-name(parameter-list) { body of function; } Function may return any type of data except an array. Parameter list are comma-separated list of variables names & their associated types. Function may be without parameter, in which case the parameter list is empty. Even if there are no formal parameters, the parenthesis is still required. The code that constitutes the body of function is hidden from the rest of the program. Parameter-list in the function definition are called formal parameters. They are the way the calling program can pass message to function for process. Formal parameters behave like other local variables inside function. They are created the moment function is called and destroyed the moment function exited. Such a parameters in C++ are call-by-value. Example: #include const char BELL = '\a'; //function definition for repeated bell ringing void ring(int k) { int i; for (i = 0; i < k; ++i) cout << BELL; } int main() { int n; cout << "\nInput a small positive integer: "; cin >> n; ring(n); // function call }
Visit : www.EasyEngineeering.net
37 Visit : www.EasyEngineeering.net
THE RETURN STATEMENT The return statement is used for two purposes. So the return statement has following two form: return; return expression; (i) when first form is encountered in the function, program control is immediately passed back to the calling environment. (ii) when the second form is used, then the value of the expression is returned to the calling program as well. Some examples are: return; return 3; return (a + b); Example: #include //find the minimum of two ints. int min(int x, int y) { if (x < y) return x; else return y; } int main() { int j, k, m; cout << "Input two integers: "; cin >> j >> k; m = min(j, k); cout << '\n' << m << " is the minimum of " << j << " and " << k << endl; }
Storage Classes in C++ Storage classes are used to specify the lifetime and scope of variables. How storage is allocated for variables and how variable is treated by complier depends on these storage classes. These are basically divided into 5 different types : 1. Global variables 2. Local variables 3. Register variables
Visit : www.EasyEngineeering.net
38 Visit : www.EasyEngineeering.net
4. Static variables 5. Extern variables Global Variables These are defined at the starting , before all function bodies and are available throughout the program. using namespace std; int globe; // Global variable void func(); int main() { ..... }
Local variables They are defined and are available within a particular scope. They are also called Automatic variable because they come into being when scope is entered and automatically go away when the scope ends. The keyword auto is used, but by default all local variables are auto, so we don't have to explicitly add keyword auto before variable dedaration. Default value of such variable is garbage.
Register variables This is also a type of local variable. This keyword is used to tell the compiler to make access to this variable as fast as possible. Variables are stored in registers to increase the access speed. But you can never use or compute address of register variable and also , a register variable can be declared only within a block, that means, you cannot have global or static register variables.
Static Variables Static variables are the variables which are initialized & allocated storage only once at the beginning of program execution, no matter how many times they are used and called in the program. A static variable retains its value until the end of program. void fun()
Visit : www.EasyEngineeering.net
39 Visit : www.EasyEngineeering.net
{ static int i = 10; i++; cout << i; } int main() { fun(); // Output = 11 fun(); // Output = 12 fun(); // Output = 13 } As, i is static, hence it will retain its value through function calls, and is initialized only once at the beginning. Static specifiers are also used in classes, but that we will learn later.
Extern Variables This keyword is used to access variable in a file which is declared & defined in some other file, that is the existence of a global variable in one file is declared using extern keyword in another file.
Introduction to Classes and Objects The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating instance of that class. The variables inside class definition are called as data members and the functions are called member functions.
Visit : www.EasyEngineeering.net
40 Visit : www.EasyEngineeering.net
For example : Class of birds, all birds can fly and they all have wings and beaks. So here flying is a behavior and wings and beaks are part of their characteristics. And there are many different birds in this class with different names but they all posses this behavior and characteristics. Similarly, class is just a blue print, which declares and defines characteristics and behavior, namely data members and member functions respectively. And all objects of this class will share these characteristics and behavior. More about Classes 1. Class name must start with an uppercase letter. If class name is made of more than one word, then first letter of each word must be in uppercase. Example, class Study, class class1 etc 2. Classes contain, data members and member functions, and the access of these data members and variable depends on the access specifiers (discussed in next section). 3. Class's member functions can be defined inside the class definition or outside the class definition. 4. Class in C++ are similar to structures in C, the only difference being, class defaults to private access control, where as structure defaults to public. 5. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc. 6. Objects of class holds separate copies of data members. We can create as many objects of a class as we need. 7. Classes do posses more characteristics, like we can create abstract classes, immutable classes, all this we will study later. Objects Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are instances of class, which holds the data variables declared in class and the member functions work on these class objects. Each object has different data variables. Objects are initialised using special class functions called Constructors. We will study about constructors later. And whenever the object is out of its scope, another special class member function called Destructor is called, to release the memory reserved by the object. C++ doesn't have Automatic Garbage Collector like in JAVA, in C++ Destructor performs this task. class Abc { int x; void display(){} //empty function }; in main()
Visit : www.EasyEngineeering.net
41 Visit : www.EasyEngineeering.net
{ Abc obj; // Object of class Abc created }
Member Functions in Classes Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class. If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name. Example : class Cube { public: int side; int getVolume(); };
// Declaring function getVolume with no argument and return type int.
If we define the function inside class then we don't not need to declare it first, we can directly define the function. class Cube { public: int side; int getVolume() { return side*side*side; } };
//returns volume of cube
But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside. class Cube { public: int side;
Visit : www.EasyEngineeering.net
42 Visit : www.EasyEngineeering.net
int getVolume(); } int Cube :: getVolume() { return side*side*side; }
// defined outside class definition
The maine function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator. int main() { Cube C1; C1.side=4; // setting side value cout<< "Volume of cube C1 ="<< C1.getVolume(); } Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition. Types of Member Functions We already know what member functions are and what they do. Now lets study some special member functins present in the class. Following are different types of Member functions, 1. 2. 3. 4. 5.
Simple Member functions These are the basic member function, which dont have any special keyword like static etc as prefix. All the general member functions, which are of below given form, are termed as simple and basic member functions. return_type functionName(parameter_list) { function body; }
Visit : www.EasyEngineeering.net
43 Visit : www.EasyEngineeering.net
Static Member functions Static is something that holds its position. Static is a keyword which can be used with data members as well as the member functions. We will discuss this in details later. As of now we will discuss its usage with member functions only. A function is made static by using static keyword with function name. These functions work for the class as whole rather than for a particular object of a class. It can be called using the object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. Example : class X { public: static void f(){}; }; int main() { X::f(); // calling member function directly with class name } These functions cannot access ordinary data members and member functions, but only static data members and static member functions. It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study about "this" keyword later. Const Member functions We will study Const keyword in detail later, but as an introduction, Const keyword makes variables constant, that means once defined, there values can't be changed. When used with member function, such member functions can never modify the object or its related data members. //Basic Syntax of const Member Function void fun() const {}
Visit : www.EasyEngineeering.net
44 Visit : www.EasyEngineeering.net
Inline functions All the member functions defined inside the class definition are by default declared as Inline. We will study Inline Functions in details in the next topic.
Friend functions Friend functions are actually not class member function. Friend functions are made to give private access to non-class functions. You can declare a global function as friend, or a member function of other class as friend. Example : class WithFriend { int i; public: friend void fun(); // Global function as friend }; void fun() { WithFriend wf; wf.i=10; // Access to private data member cout << wf.i; } int main() { fun(); //Can be called directly }
Hence, friend functions can access private data members by creating object of the class. Similarly we can also make function of other class as friend, or we can also make an entire class as friend class.
class Other { void fun(); }; class WithFriend
Visit : www.EasyEngineeering.net
45 Visit : www.EasyEngineeering.net
{ private: int i; public: void getdata(); // Member function of class WithFriend friend void Other::fun(); // making function of class Other as friend here friend class Other; // making the complete class as friend };
When we make a class as friend, all its member functions automatically become friend functions. Friend Functions is a reason, why C++ is not called as a pure Object Oriented language. Because it violates the concept of Encapsulation.
Function Overloading If any class have multiple functions with same names but different parameters then they are said to be overloaded. Function overloading allows you to use the same name for different functions, to perform, either same or different functions in the same class. Function overloading is usually used to enhance the readability of the program. If you have to perform one single operation but with different number or types of arguments, then you can simply overload the function.
Ways to overload a function 1. By changing number of Arguments. 2. By having different types of argument.
Number of Arguments different In this type of function overloading we define two functions with same names but different number of parameters of the same type. For example, in the below mentioned program we have made two sum() functions to return sum of two and three integers. int sum (int x, int y) { cout << x+y; } int sum(int x, int y, int z)
Visit : www.EasyEngineeering.net
46 Visit : www.EasyEngineeering.net
{ cout << x+y+z; } Here sum() function is overloaded, to have two and three arguments. Which sum() function will be called, depends on the number of arguments. int main() { sum (10,20); // sum() with 2 parameter will be called sum(10,20,30); //sum() with 3 parameter will be called }
Different Datatype of Arguments In this type of overloading we define two or more functions with same name and same number of parameters, but the type of parameter is different. For example in this program, we have two sum() function, first one gets two integer arguments and second one gets two double arguments. int sum(int x,int y) { cout<< x+y; } double sum(double x,double y) { cout << x+y; } int main() { sum (10,20); sum(10.5,20.5); }
Default Arguments When we mention a default value for a parameter while declaring the function, it is said to be as default argument. In this case, even if we make a call to the function without passing any value for that parameter, the function will take the default value specified. sum(int x,int y=0) {
Visit : www.EasyEngineeering.net
47 Visit : www.EasyEngineeering.net
cout << x+y; } Here we have provided a default value for y, during function definition. int main() { sum(10); sum(10,0); sum(10,10); } Output : 10 10 20
First two function calls will produce the exact same value. for the third function call, y will take 10 as value and output will become 20. By setting default argument, we are also overloading the function. Default arguments also allow you to use the same function in different situations just like function overloading. Rules for using Default Arguments 1. Only the last argument must be given default value. You cannot have a default argument followed by non-default argument. 2. sum (int x,int y); 3. sum (int x,int y=0); 4. sum (int x=0,int y); // This is Incorrect 5. If you default an argument, then you will have to default all the subsequent arguments after that. 6. sum (int x,int y=0); 7. sum (int x,int y=0,int z); // This is incorrect 8. sum (int x,int y=10,int z=10); // Correct 9. You can give any value a default value to argument, compatible with its datatype.
Placeholder Arguments When arguments in a function are declared without any identifier they are called placeholder arguments. void sum (int,int);
Visit : www.EasyEngineeering.net
48 Visit : www.EasyEngineeering.net
Such arguments can also be used with default arguments. void sum (int, int=0);
Operator Overloading Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. For example '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.
Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows
scope operator - :: sizeof member selector - . member pointer selector - * ternary operator - ?:
Visit : www.EasyEngineeering.net
49 Visit : www.EasyEngineeering.net
Operator Overloading Syntax
Implementing Operator Overloading Operator overloading can be done by implementing a function which can be : 1. Member Function 2. Non-Member Function 3. Friend Function Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand is different, then Operator overloading function must be a nonmember function. Operator overloading function can be made friend function if it needs access to the private and protected members of class.
Restrictions on Operator Overloading Following are some restrictions to be kept in mind while implementing operator overloading. 1. Precedence and Associativity of an operator cannot be changed. 2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc. 3. No new operators can be created, only existing operators can be overloaded. 4. Cannot redefine the meaning of a procedure. You cannot change how integers are added. Operator Overloading Examples Almost all the operators can be overloaded in infinite different ways. Following are some examples to learn more about operator overloading. All the examples are closely connected.
Visit : www.EasyEngineeering.net
50 Visit : www.EasyEngineeering.net
Overloading Arithmetic Operator Arithmetic operator are most commonly used operator in C++. Almost all arithmetic operator can be overloaded to perform arithmetic operation on user-defined data type. In the below example we have overridden the + operator, to add to Time(hh:mm:ss) objects.
Example: overloading '+' Operator to add two time object #include< iostream.h> #include< conio.h> class time { int h,m,s; public: time() { h=0, m=0; s=0; } void getTime(); void show() { cout<< h<< ":"<< m<< ":"<< s; } time operator+(time); //overloading '+' operator }; time time::operator+(time t1) //operator function { time t; int a,b; a=s+t1.s; t.s=a%60; b=(a/60)+m+t1.m; t.m=b%60; t.h=(b/60)+h+t1.h; t.h=t.h%12; return t; } void time::getTime() { cout<<"\n Enter the hour(0-11) "; cin>>h; cout<<"\n Enter the minute(0-59) "; cin>>m;
Visit : www.EasyEngineeering.net
51 Visit : www.EasyEngineeering.net
cout<<"\n Enter the second(0-59) "; cin>>s; } void main() { clrscr(); time t1,t2,t3; cout<<"\n Enter the first time "; t1.getTime(); cout<<"\n Enter the second time "; t2.getTime(); t3=t1+t2; //adding of two time object using '+' operator cout<<"\n First time "; t1.show(); cout<<"\n Second time "; t2.show(); cout<<"\n Sum of times "; t3.show(); getch(); }
Overloading I/O operator
Overloaded to perform input/output for user defined datatypes. Left Operand will be of types ostream& and istream& Function overloading this operator must be a Non-Member function because left operand is not an Object of the class. It must be a friend function to access private data members.
You have seen above that << operator is overloaded with ostream class object cout to print primitive type value output to the screen. Similarly you can overload << operator in your class to print user-defined type to screen. For example we will overload << in time class to display time object using cout. time t1(3,15,48); cout << t1; 1.4 REFERENCE VARIABLE INITIALIZATION A reference variable is an alias, that is , another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the refrence name must be used to refer to the variable. 1.4.1. DIFFERENCE BETWEEN REFERENCE AND POINTERS
Visit : www.EasyEngineeering.net
52 Visit : www.EasyEngineeering.net
References are often confused with pointers with pointers but three major differences between references and pointers are : We cannot have NULL references. We 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. Pointers can be initialized at any time. 1.4.2. CREATION OF REFERENCE VARIABLE Variable name as a label attached to the variable’s location in memory. We can then think of a reference as a second label attached to that memory location. We can access the contents of the variable through either the original variable name or the reference. 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” #include int main( ) { int i; double d; int& r=i; double& s=d; i=5; cout<<”value of i :”<
Visit : www.EasyEngineeering.net
53 Visit : www.EasyEngineeering.net
It provides more reliable and flexible. Functions can be overloaded to make it perform different tasks depending on the arguments passed to it. Type of Functions C++ functions classified into two types. (1) Built in function (2) User defined functions Built – in Functions These functions are part of the compile package. These part of standard library made available by the compiler. Example : exit(), sqrt(), pow(), strlen(),etc.,
User defined functions The user defined functions are created by the programmer. These functions are created as per requirements of our program. Function Definition A function must be defined before it is used anywhere in the program. The general form of function definition is : type function name(parameter list) { body of the function } where the type specifies the type of value that the return statement of the function.
If no type sis specified, the compiler assumes that the function returns an integer value. The parameter list is a list of variables separated by comma, referred as function arguments. A function definition must have a return statement. FUNCTION PROTOTYPE function prototype is not required for every function definition in the program. If function-call encountered before function definition, then function prototype is required. In C++ all function must be declared before they are used. This is normally accomplished using function prototype. The function prototype has the following general form: return-type function-name(argument-declaration-list); The argument-declaration-list is either empty, or a single declaration, or a comma separated list of declarations. If the function has not parameters, the keyword void may be used. Example:
Visit : www.EasyEngineeering.net
54 Visit : www.EasyEngineeering.net
//Add three ints -illustrating function prototypes. #include
int add3(int, int, int); double average(int); int main() { int score_1, score_2, score_3, sum; cout << "\nEnter 3 scores: "; cin >> score_1 >> score_2 >> score_3; sum = add3(score_1, score_2, score_3); cout << "\nTheir sum is " << sum; cout << "\nTheir average is " << average(sum); } int add3(int a, int b, int c) { return (a + b + c); } double average(int s) { return (s / 3.0); } C++ uses ellipsis symbol(…) to indicate that an argument list that is unspecified. For example, the function printf( ) prototype is given below: int printf( const char* cntrl_str,…); Such a function can be invoked on an arbitrary list of actual parameters Need For Prototypes Function prototyping enables a compiler to carefully compare each use of the function with the prototype of determine whether the function is invoked properly. Accesssing a Function
A function is called by providing the function name, followed by the parameters enclosed in braces. The general form for accessing a function is function name(argument list) Example : area(x,y); Default Arguments C++ allow to call a function without specifying all the arguments. In such cases, function assigns a default value to the parameter. Default values are specified at the time of function declaration.
Visit : www.EasyEngineeering.net
55 Visit : www.EasyEngineeering.net
Constant Arguments An argument to a function can be declared as const. The qualifier const tells the compiler that the function should not modify the argument. The constant arguments are useful when the functions are called by reference. Example : int sum(const int a,const int b); int length(const string &s);
Visit : www.EasyEngineeering.net
56 Visit : www.EasyEngineeering.net
Call by Value and Call by Reference in C++ On the basis of arguments there are two types of function are available in C++ language, they are;
With argument Without argument
If a function take any arguments, it must declare variables that accept the values as a arguments. These variables are called the formal parameters of the function. There are two ways to pass value or data to function in C++ language which is given below;
call by value call by reference
Visit : www.EasyEngineeering.net
57 Visit : www.EasyEngineeering.net
Call by value In call by value, original value can not be changed or modified. In call by value, when you passed value to the function it is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller function such as main().
#include #include void swap(int a, int b) { int temp; temp=a; a=b; b=temp; } void main() { int a=100, b=200; clrscr(); swap(a, b); // passing value to function cout<<"Value of a"<
Visit : www.EasyEngineeering.net
The Northeast Office serves a sixteen county area including Bradford, Carbon, Columbia, Lackawanna, Lehigh, Luzerne,. Monroe, Montour, Northampton, Northumberland, Pike, Schuylkill, Sullivan, Susquehanna, Wayne and Wyoming Counties. The Council has o
Wilkes University. The Pennsylvania Environmental Council is a statewide nonprofit organization dedicated toward protecting and. restoring the natural and built ...
AKAD NOTARIS. Serius Hub. : Dr. DJAFAR. Raya Kutisari Utara 46 Surabaya,. Telp : 081217185318. AIR ZAM-ZAM. istimewa. Direktur GTK Madrasah Suyitno (tengah mengenakan udeng) sedang bercengkrama dengan guru. Page 3 of 5. PEC- Image of Success Oct. 201
To the Provincial Elders Conference of the Moravian Church, Northern Province ... from Gods Word and know that it is more important to trust and obey God ...
Sign in. Page. 1. /. 4. Loading⦠Page 1 of 4. Page 1 of 4. Page 2 of 4. Page 2 of 4. Page 3 of 4. Page 3 of 4. PEC- Image of Sucess 2010.pdf. PEC- Image of Sucess 2010.pdf. Open. Extract. Open with. Sign In. Main menu. Displaying PEC- Image of Suce
was directed by the General Assembly in 2016 to restart their rulemaking for the conventional industry. It is our understanding that DEP is ... Pennsylvania Environmental Council. Page 2 of 2. EDF PEC SB1088 Comments. 11 April 2018.pdf. EDF PEC SB108
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. PEC DEFINITIVO 13-11-09.pdf. PEC DEFINITIVO 13-11-09.pdf.
Invitation for Internal audit of accounts for PEC University of Technology.pdf. Invitation for Internal audit of accounts for PEC University of Technology.pdf. Open.