Sie sind auf Seite 1von 25

Introduction

Introduction to C++ world Setting up C++ in computer Compatibility issues My First c++ program Common errors Comments Why variables? Why so many variables Using variables in C++ Identifiers Global Variables AND Local Variables Fundamental data types Int Char Float etc Compound data types Struct Array Character sequence Other data types Typredef Enum Union Constants Assignment Arithmetic Increment, decrement Compound assignment Relational &&, ||, ?, , Sizeof Precedence operator Cin Cout If else While Do while For Jump Continue Goto Exit Switch Declaring function Calling function Parameters with function Pass by vaue,. Pass by reference Overloaded function Inline function Recursion New Delete Constructor and destructor Overloading constructor

Variables

Datatypes

Operators

Input /output

Control

Function

Memory

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

Classes

Default constructor Inheritance Friendship Multiple Inheritacne

Pointers

Reference De-reference Declaring variables Pointers and arrays Pointer initialize Pointer to pointer Void pointer Null pointer Pointer to function Pointer to structure Pointer to class Exception handling Type casting Polymorphism Abstract C lass Operator Overloading Namespace

Others

Introduction to the C++ Language A C++ program is a collection of commands, which tell the computer to do "something". This collection of commands is usually called C++ source code, source code or just code. But how does a program actually start? Every program in C++ has one function, always named main, tha t is always called when your program first executes. From main, you can also call other functions whether they are written by us or, as mentioned earlier, provided by the compiler. So how do you get access to those prewritten functions? To access those s tandard functions that comes with the compiler, you include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program. Let's look at a working program: Setting Set Up - C++ Compilers The very first thing you need to do, before starting out in C ++, is to make sure that you have a compiler. What is a compiler, you ask? A compiler turns the program that you write into an executable that your computer can actually understand and run. Some common compilers include Borland C ++, Microsoft C++, and GNU C++. Each of these compilers is slightly different. Each one shou ld support the ANSI/ISO standard C ++ functions, but each compiler will also have nonstandard functions (these functions are simi lar to slang spoken in different parts of a country). Sometimes the use of nonstandard functions will cause problems when you attemp t to compile source code (the actual C++ written by a programmer and saved as a text file) with a different compiler. Compatibility Issues in compilation The ANSI-C ++ standard was recently accepted as an international standard. The C++ language exists from a long time before (1980s). Therefore there are many compilers which do not support all the new capabilities included in ANSI-C++, especially those released prior to the publication of the standard. Therefore output of a program is compiler dependant. Also many new program s dont run on old compiler. So please make sure that you have latest compiler in your machine. My first Hello India program in c ++ // my first hello world program in C++ #include <iostream.h> void main () { cout << "Hello India"; } Now lets understand the code we have written: // my first hello India program in C++

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The programmer can use them to include short explanations or observations within the source code its elf. In this case, the line is a brief description of what our program is. #include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream header file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program. We will use more includes in our future programs. Here cout function is defined in iostream.h file. void main () This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (()). cout << "Hello India"; This line is a C++ statement. cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello India sequence of characters) into the standard output stream (which usually is the screen). cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that specific file and to declare that we were going to use this specific namespace earlier in our code. Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement). Common Errors when Declaring Variables in C++ 1. Undeclared variable: If you attempt to use a variable that you have not declared, your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable. 2. Case Sensitivity: Now is a good time to talk about an important concept that can easily throw you off: case sensitivity. Basically, in C ++, whether you use uppercase or lowercase letters matters. The words Cat and cat mean different things to the compiler. In C++, all language keywords, all functions and all variables are case sensitive. A difference in case between your variable declaration and the use of the variable is one reason you might get an undeclared variable error.

Comments Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: 1. // line comment 2. /* block comment */ The first of them, known as line comment, discards everything from where the pair of slash signs ( //) is found up to the end of that same line. The second one, known as block comment, discards everything between the /* characters and the first appearance of the */ characters, with the possibility of including more than one line. Why variables? Variables are used to store values that can be used by program. Also it is used to pass value from user to computer. A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and variables of type float store numbers with decimal places. Each of these variable types - char, int, and float - is each a keyword that you use when you declare a variable. Why so many variable types? We use so many variable types to make your code efficient and readable. Using the right variable type can be important for ma king your code readable and for efficiency--some variables require more memory than others. E.g.: Char should not be used to store number. Float should be used only if you want to store decimal. Declaring Variables in C++ To declare a variable you use the syntax "type <name>;". Here are some variable declaration examples: int x; char student_name; float cost_price;

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma. int a, b, c, d; If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon (note that this is the same procedure used when you call a function). Using Variables Ok, so you now know how to tell the compiler about variables, but what about us ing them? One application of variable is an addition program. Suppose you want to add two numbers, in that case you have to put number1 and number2 in memory and then add it. In such case you will need variable. Int a = 6; Int b = 3; Int result = a + b;

Identifiers A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Rules for identifiers: 1. Identifiers are case sensitive. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters 2. Neither spaces nor punctuation marks or symbols can be part of an identifier. 3. Only letters, digits and single underscore characters are valid. 4. Variable identifiers always have to begin with a letter or an underline character (_ ). 5. In no case can they begin with a digit. 6. Identifiers cannot match any keyword of the C ++ language nor your compiler's specific ones, which are reserved keywords. The standard reserved keywords are: asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, pr ivate, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while Some operators cannot be used as identifiers since they are reserved words under some circumstances: and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Local and Global Variables A variable can be either of global or local scope. A global variable is a variable declared i n the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared.

Fundamental data types When we wish to store data in a C++ program, such as a whole number or a character, we have to tell the compiler which type of data we want to store. The data type will have characteristics such as the range of values that can be stored and the operati ons that can be performed on variables of that type. Fundamental types C++ provides the following fundamental built-in data types: Boolean, character, integer and floating-point. Boolean Type The Boolean type can have the value true or false. For example: bool flag = false; If a Boolean value is converted to an integer value true becomes 1 and false becomes 0 and vice versa. Character Type The character type is used to store characters - typically ASCII characters but not always. For example: char alphabet = 'a'; char number = '52'; We can declare signed and unsigned characters, where signed characters can have positive and negative values, and unsigned characters can only contain positive values. A char is guaranteed to be at least 8 bits in size. Integer Types The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer values as follows:

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

signed int marks = -187; unsigned int vote = 12; int population = 998100; Like characters, signed integers can hold positive or negative values, and unsigned integers can hold only positive values. However, plain integer can always hold positive or negative values, they're always signed. Integer values come in three sizes, plain int, short int and long int. The range of values for these types will be defined by your compiler. A short integer is guaranteed to be at least 16 bits and a long integer at least 32 bits. Floating-Point Types Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float (single-precision), double (double-precision) and long double (extended-precision). Some examples: float celsius = 37.623; double fahrenheit = 98.415; long double accountBalance = 1897.23; The range of values that can be stored in each of these is defined by your compiler . Name char short int (short) int Description Character or small integer. Short Integer. Integer. Size* 1byte 2bytes 4bytes Range* signed: -128 to 127 unsigned: 0 to 255 signed: -32768 to 32767 unsigned: 0 to 65535 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 true or false +/- 3.4e +/- 38 (~7 digits) +/- 1.7e +/- 308 (~15 digits) +/- 1.7e +/- 308 (~15 digits) 1 wide character

long int (long) Long integer. bool float double long double wchar_t

4bytes

Boolean value. It can take one of two values: true or 1byte false. Floating point number. Double precision floating point number. Long double precision floating point number. Wide character. 4bytes 8bytes 8bytes 2 or 4 bytes

* The values of the columns Size and Range depend on the system the program is comp iled for. Composite data type: A composite data type is any data type which can be constructed in a program using primitive data types and other composite types. Examples of composite data types are enum, struct, class, string etc Structs or Structures There are many instances in programming where we need more than one variable in order to represent something. For example, to represent student, you might want to store name, age, address, phone number etc, or any other number of characteristics about student. You could do so like this: char strName[20]; int age;Char address[50]; int phoneNumber; However, you now have 4 independent variables that are not grouped in any way. If you wanted to pass information about yourse lf to a function, youd have to pass each variable individually. Furthermore, if you wanted to store information about more people, youd have to declare 4 more variables for each additional student. Fortunately, C++ allows us to create our own user-defined aggregate data types. An aggregate data type is a data type that groups multiple individual variables together. One of the simplest aggregate data type is the struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit. Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct declaration: struct Student { char strName[20]; int age;

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

Char address; Int phoneNumber; } This tells the compiler that we are defining a struct named Student. The Employee struct contains 4 variables inside of it: t wo ints and two char. These variables are called members (or fields). Keep in mind that the above is just a declaration even though we are telling the compiler that the struct will have variables, no memory is allocated at this time. In order to use the Employee struct, we simply declare a variable of type Employee: Student s1, s2; Using this command we create objects of student , S1 and S1 and hence memory is allocated. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 10 values of type int in an array without having to declare 10 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier. Int arrayStudentId[10]; This can store 10 student ids.. arrayStudentId[0]= 123; arrayStudentId[1]= 124; etc.. int int int int int int employeeId[5] employeeId[0] employeeId[1] employeeId[2] employeeId[3] employeeId[4] = { 1,2,3,4,5}; // this is array of length 5, and it is similar to = 1; = 2; = 3; = 4; = 5;

Multi Dimensional array: int ExamFear[3][4]; It is represented internally as:

0 0 1 2

How to access the elements in the Multidimensional Array 0 0 1 2 1 2 3

Highlighted cell represent ExamFear[1][2]

Enumerated types An enumerated type is a data type where every possible value is defined as a symbolic constant (called an enumerator). Enumerated types are declared via the enum keyword. Lets look at an example: enum Color_list {C OLOR_BLACK, COLOR_RED, COLOR_BLUE}; Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is declared memory is allocated for that variable at that time. Enum variables are the same size as an int variable. This is because each enumerator is automatically assigned an integer value based on its position in the enumeration list. By default, the first enumerator is assign ed the integer value 0, and each subsequent Page

Visit ExamFear.com for Free Question Papers for almost all Exams.

enumerator has a value one greater than the previous enumerator:

Typedefs Typedefs allow the programmer to create an alias for a data type, and use the aliased name instead of the actual type name. T o declare a typedef, simply use the typedef keyword, followed by the type to alias, followed by the alias name . A typedef does not define new type, but is just another name for an existing type. A typedef can be used anywhere a regular type can be used. typedef int StudentId; // define StudentId as an alias for int // The following two statements are equivalent: Int CollegeStudentId; StudentId CollegeStudentId; Typedefs are used mainly for documentation and legibility purposes.

Unions Unions allow one same portion of memory to be accessed as different data types, since all of them are in fact the same location in memory. Its declaration and use is similar to the one of structures but its functionality is totally different: union memory_save { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; All the elements of the union declaration occupy the same physical space in memory. Its size is the one of the greatest element of the declaration. Since all of them are referring to the same location in memory, the modification of one of the elements will affect the value of all of them. We cannot store different values in them independent of each other. Defined constants (#define) You can define your own names for constants that you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is: #define identifier value For example: #define Rupee_dollar_conversion 43.8 This defines a new constant: Rupee_dollar_conversion. Once it is defined, you can use it in the rest of the code as if they were any other regular constant, Declared constants (const) With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: const int team_count = 11; const char team_name = 'India'; Here, team_count and team_name are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

Operators

Operator is used to operate variables and constants. Lets discuss various kinds of operators in C++. Assignment (=) This operator assigns a value to a variable. E.g : int i = 10; This statement assigns the integer value 10 to the variable i. The part at the left of the assignment operator (=) is variable whereas the one on right is constant. The assignment operation always takes place from right to left only.

Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C ++ langua ge are: + addition - subtraction

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

* multiplication / division % modulo Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. Modulo is the operation that gives the remainder of a division of two values. For example, if we write: int b = 10 % 4; the variable a will contain the value 2, since 2 is the remainder from dividing 10 by 4. Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) Compound assignment operators are used when we want to modify the value of a variable by performing an operation on the value that is stored in the variable currently. Usage Example: p -= 6; p = p - 6; p /=q; p = p / q; a *= b - 5; a = a * (b -5); Increase and decrease (++, --) Increase operator (++) and the decrease operator (--) increase or decrease by one the value stored in a variable. a++ ;a+=1; a=a+1; are all same. All increase value of a by 1. b--;b-=1;b=b-1; are all same. All decrease value of b by 1 Difference between a++ and ++a: In case of (++a) the value is increased before the result of the expression is evaluated while in case of (a++) the value stored in a is increased after being evaluated. Lets see the example to clarify any doubts if any. P=5; Q= ++P; //Here both P and Q stores 6. P=5; R = P++; //Here R stores 5 and P stores 6. Relation and equality operator: Relational and equality operators are used to compare between two expressions. The result of a relational operation is a Boolean value that can only be true or false. == Equal to != Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to Lets see some examples to clarify doubts if any. (5== 2) // this returns false. (5!= 5) // this returns false. (5<2) // this returns false. (2>5) // this returns false. (5==5) // this returns true (5!=2 ) // this returns true (2<5) // this returns true (5>2) // this returns true

&& OPERATOR This is AND operator. For A && B, if both A and B are true, result is true else it is false. Even if one is false, result is false. || Operator: This is logical OR operator. For A && B, even if either of A or B is true, result is true. It is false only when both A and B are false. Conditional operator ( ? ) The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: variable = condition ? result1 : result2 If condition is true the expression will return result1, if it is not it will return result2. A = 9<5 ? 5 : 6 // returns 6, since 9 is not greater than 5. Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. For example, the following code: p = (q=4, q+3);

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

Here q is assigned 4 in first place, then q+3, that is (4+3 =7) is assigned to P. Explicit type casting operator Type casting operators are used to convert a variable from on type to another type. This is done by writing by the new type enclosed between parentheses (()): float float_vlaue = 5.234; int integer_value =0; integer_value = (int) float_vlaue; The above code converts float float_vlaue to int. here integer_value stores values 5 as decimal place is lost in type conversion. Type casting can also be done in the syntax mentioned below. integer_value = int (float_value ); sizeof() This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution.

Input/Output in C++
C++ uses streams to perform input and output operations. A stream is an object where a program can either insert or extract characters to/from it. Header file iostream.h defines methods for input output using streams. Standard Output (cout) By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs). cout << "Hello"; // prints Hello cout << Hello; // prints the content of Hello variable The insertion operator (<<) may be used more than once in a single statement: cout << "Hello, " << "I am " << "a C++ statement"; It is important to notice that cout does not add a line break after its output unless we explicitly indicate it. Standard Input (cin). The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example: int age; cin >> age; The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced.

Control Structures
In real world, we need scenarios where program need to take decision, jump to code in some other place, repeat code etc. This cant be achieved by linear sequence of instructions. So we have concept of control structures. Before we proceed further, let me introduce you to a concept called block. Block is a group of sentence that are enclosed in {}; Eg: { int a; char b; float c;} if and else The if keyword is used to execute a piece of statement or block only when a given condition is true. Else statement is used to execute a piece of statement or block only when a given statement is false. Syntax: If ( condition) { Execute this block if condition is true} else Page

Visit ExamFear.com for Free Question Papers for almost all Exams.

{ Execute this block if condition is false} Eg: if (a == b) {C ount << both a and b are equal} else {C ount << both a and b are not equal} Iteration structures (loops) Loop is used when we want a block to be executed certain number of times. Format: while (Condition is true) { statements to be executed } In this case, the statements will be executed till the condition is true. While(true) {count<< this is a tutorial by examfear.com ; } This will execute infinite number of times. Int i=10; While(i>0) { count<< this is a tutorial by examfear.com ; i--; } This statement will be executed 10 times. Do-while loop Do while loop and while loop are almost similar with a difference that do while loop is executed at least once even if the co ndition is false. This is because condition in the do-while loop is evaluated after the execution of statement instead of before. Syntax: do {statements to be executed} while (condition); int i=10; do { count<< this is a tutorial by examfear.com ; } while (i ==5) This statement will be executed once even when the condition is false int i=10; while (i ==5 { count<< this is a tutorial by examfear.com ; } This statement will not be executed even once. The break statement Break statement is used to come out of a loop evein if condition is not fulfilled. while(true) { cout<< this document is brought to you by examfear.com; break; } Without break statement, this loop will print infinite times, but sine we have placed a break statement, the cout statement will be executed only once.

The continue statement

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

10

The continue statement is used to skip rest of the loop and goes back to the start of the current iteration as if end of the block is reached. Suppose we want to print odd numbers from 1 to 10. then we can use continue statement to skip printing of even number. int i = 0; while ( i <10) {i++; if(i%2 == 0) continue; cout<< i; }

// if the number is even, it will return true and hence we will skip the next statement.

The goto statement goto statement is used when we want to jump to another point in the program. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). Suppose we want to print odd numbers from 1 to 10. then we can use continue statement to skip printing of even number. int i = 0; while ( i <10) {i++;s if(i%2 == 0) Label1234; cout<< i; Label1234: }

// if the number is even, it will return true and hence we will to label1234.

The exit function The purpose of exit is to terminate the current program with a specific exit code. exit is a function defined in the cstdlib library . Syntax: void exit (int exitcode); The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened. Switch statement. Switch statement is used to check several possible values for an expression and then decide to execute a statement or block based on that value. switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } Working of switch statement: 1. It evaluates expression. It should be some constant. 2. Based on the value it goes to case <<value of expresion>> statement 3. It executes the statement till it encounters a break statement. That is why block is not needed in s witch. 4. If the expression value is not equal to any of the constant value then it executes statements after default: switch (a) { case 1: cout << "a is 1; break; case 2: cout << "a is 2; break; case 3: cout << "a is 3; break; default: cout << "a is unknown"; } This code will print a is 1 is a ==1; a is 2 if a==2; a is 3 if a==3 and a is unknown if a is any other number. Please note the break statement.

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

11

Functions

In real world programming, code is huge. It is difficult to manage code if it is not structured. Also in most of the case we use same logic at multiple places, so it doesnt make any sense to write same block of code multiple times. Hence come s the concept of function. Advantage of functions: 1. Make code more structures 2. Make code more human readable 3. Re-use of same block of code at multiple places. A function is a group of statements that is executed when it is called from some point of the program. The following is its format: type name ( parameter1, parameter2, ...) { statements } where: 1. type is the data type returned by the function. E.g.: if it is Int, it means that function return integer. 2. name is the identifier by which it will be possible to call the function. 3. parameters: Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int a) and which acts within the function as regular local variable. 4. statements is the function's body. It is a block of statements surrounded by braces { }.It is the bunch og code that needs to be executed on function call. Here you have the first function example: // function example with constant as parameter to the function #include <iostream> int additionFx (int p, int q) { int r; r=p+q; return (r); } void main () { int a; a = additionFx (6,2); cout << "The sum of 6 and 2 is " << a; } Output: The sum of 6 and 2 is 8 Explanation: The code starts from void main() function. The first statement creates an integer a variable. In the next statement function additionFx () is called with two parameters viz 6, 2. Thus the control will now go to the function. As we notice that return type of function is integer it will return integer and the output will be stored in integer variable named a. If we go inside the fun ction than we notice that the function use two local variables p and q , that are also parameters to the function. We define a variable called r, this variable stores the sum of p and q and returns back which is now captured by a. And finally the number a is printed.

// function example with variable as parameter to the function #include <iostream> int additionFx (int p, int q) { int r; r=p+q; return (r); } void main () { int a,b,c; b=6; c=2;

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

12

a = additionFx (b,c); cout << "The sum of 6 and 2 is " << a; } Output: The sum of 6 and 2 is 8 Explanation: This program is similar to what mentioned above with only one difference. Instead of passing constant values 2 and 6 to function, now we are passing variables to the function. This works perfectly fine. Functions with no return type: If you want to create a function that doesnt return any data type then you will have to use void as return type. Eg: void printvalue(int i); //Example of function with no return type #include <iostream> void printvalue (int i) { cout << "The value of number passed is+ << i; }void main () { int a=5; printvalue (a); } Arguments passed by value and by reference. In the function examples we have seen till now, the values of variables are passed as arguments to the function. void modifyArgument (int p, int q) { p = p+1; q= q+1; } void main () { int b,c; b=6;c=2; modifyArgument (b,c); cout << "The value of b is " << b; cout << "The value of c is " << c; } Output: The value of b is 6. The value of c is 2 Here values of b and c, viz 6 and 2 are passed to the function as the argument defined while creating function is of type int. Thus even if we change the value of p and q in the function it doesnt change the value of a and b as int p == 6 not b int q == 2 not c The key point here is that values (6, 2) of variable ( b, c) are passed to the function. The variables are not passed. So any change done inside the function is change done to values of variable not the variable. Now lets us look at the code, where variables are passed to the function instead of values. void modifyArgument (int& p, int& q) { p = p+1; q= q+1; } void main () { int b,c; b=6;c=2;

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

13

modifyArgument (b,c); cout << "The value of b is " << b; cout << "The value of c is " << c; } Output: The value of b is 7 The value of c is 3 In this example, parameters to function definition is not int but int&. datatype& denotes that variable not the value is to be passed to function. Thus when we say p= p+1 inside the function it increase the variable by 1. To understand this concept let us take example of bag and book. Here book is inside book. In our context bag is variable that stores value called book. Bag: Variable Book: value. Case 1: Pass by value: In this case book is passed to the function. Change is made to the book not to the bag. Hence when we try to print the bag it is still old bad. Case 2; Pass by reference: In this case bag is passed to the function. C hange is thus made to the bag not book. When we print the bag, it prints the modified bag as the bag not book was modified by the function. Default values in parameters. In real life code we have scenario where we need to pass default values to the function. This value is used when the correspo nding argument in blank at the time of calling function. This can be achieved by simply using an assignment operator and a value while calling the function. // example of default value function #include <iostream> int additionFx (int a, int b=4) { int r; r=a+b; return (r); } void main () { cout << additionFx (3); cout << , ; cout << additionFx (3,5); } 7 , 8 Explanation: When additionFx (3)is called, b takes its default value that is 4 and thus output is 3+ 4 =7; When additionFx (3,5) is called the output is 3+5 =8; Overloaded functions. To make code more readable, we need functions that perform different action if they have either differen number of parameter or different type of parameter. // Example of overloaded function #include <iostream> float area (int length, int breadth) { return (length * breadth); } float area (int radius) { return (22/7 * radius * radius); } void main () { int l=2,b=3,r=7; cout <<Area of rectangle is + area (l,b); cout <<Area of circle is +area(r); } Area of rectangle is 6 Area of circle is 154 Explanation:

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

14

Here we have two methods with same name called area. First one calculates area of rectangle while second one calculates area of circle. This is done by overloaded function. The argument to both function are different. When we call area (l,b), then first function is called that calculates area of rectangle. When we call area , then second function is called , calculating area of circle. inline functions. The inline specifier indicates the compiler that inline substitution is preferred to the us ual function call mechanism for a specific function. This does not change the behavior of a function itself, but is used to suggest to the compiler that the code generated by the function body is inserted at each point the function is called, instead of be ing inserted only once and perform a regular call to it, which generally involves some additional overhead in running time. The format for its declaration is: inline type name ( arguments ... ) { instructions ... } and the call is just like the call to any other function. You do not have to include the inline keyword when calling the function, only in its declaration. In case of normal function invocation, a call is made to a function which resides is some other location. Then a value is ret urned and the control comes back to the calling function. In case of inline function the block of code inside the function is pasted in the calling function, so there is no cal made to function actually. Most compilers already optimize code to generate inline functions when it is more convenient. This specifier only indicates the compiler that inline is preferred for this function. Recursion. Recusion is a very powerful tool in C ++. When a function calls itself it is called recursion. int functionabc() { // write some statement here Functionabc(); } Here function functionabc() calls function functionabc(). Declaring functions. Till now, we have defined function and then we have used it. If we try to do other way round it will throw error as compiler will not be aware of the function. In order to avoid this we can just declare the function before invoking it. Function definition can be provided later in this case. Syntax: type name ( argument_type1, argument_type2, ...); It is identical to a function definition, except that it does not include the body of the function and also it doesnt have braces {}. Also note the semicolon at the end of declaration. The parameter enumeration does not need to include the identifiers, but only the type specifier. Both statemen t below will work fine. int FunctionExamfear (int marks); int FunctionExamfear (int); //Example of function declaration void main () { int additionFx (int, int); int a; a = additionFx (6,2); cout << "The sum of 6 and 2 is " << a; } int additionFx (int p, int q) { int r; r=p+q; return (r); } Output: The sum of 6 and 2 is 8 Here addition function is just defined after function invocation, but still it ran successfully because of function declarati on before function calling.

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

15

Lets revise what all we can do with function. Things we can do with function: 1. Function declaration: Eg int additionFx(int,int); 2. Function invocation/call: Eg: int p =additionFx(3,2); 3. Function definition : Eg: int additionFx(int a, int b){ return (a+b);}

Dynamic Memory

Till now we have seen that fixed size memory is allocated to the variable and the size is know before execution of the program. Eg: int i; int b[5]; etc. In real world, we sometimes are not aware of the size of variable at the time of coding. It is to be decided run time. Eg: we want to store the details of users who has visited a website on a particular day. Since we dont know then number of user, we will have to allocate memory dynamically. In such scenarios we need to use dynamic memory. Operators new and new[] new operator is used to dynamically allocate memory. It returns a pointer to the beginning of the new block of memory allocated Syntax: pointer = new type pointer = new type [n] Example: int * ExamFear; ExamFear = new int [3]; Here system allocates space for 3 elements of type int and return a pointer to the first element. The first element can be accessed with expression ExamFear[0] or *ExamFear The Second element can be accessed with expression ExamFear[1] or *(ExamFear +1) The Third element can be accessed with expression ExamFear[2] or *(ExamFear +2).. etc System memory heap is allocated to the dynamic memory items and we know that system has limited memory resource, so it is advisable to delete or free the resource not in use. Operators delete and delete[] To delete the memory not in use, delete operator is used. Syntax: delete pointer; delete [] pointer; The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements. The value passed as argument to delete must be either a pointer to a memory block previously allocated with new,// to allocate memory containing one single element of type type. //to allocate memory containing n number of elements of type type.

Classes

A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format: class class_nm { access_specifier_a: member1; access_specifier_b: member2; ... function(parameters); } object_nm; Here Class_nm is unique name of class. object_nm is name of object. Access_specifier are keywords private, public or protected. These specifiers modify the access rights that the members following them acquire: Private member of a class are accessible only from members of the same class or from their friends. We will talk about friendslater. Protected members are accessible not only from members of same class and friends, but also from derived classes. Public members are accessible from anywhere where object is visible. If no access specifier is defined then it is considered private.

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

16

//Example of class class ExamFear { int x, y; public: void print_message(char); int user_id (char); } user1234; The above code defines a class called Examfear which has two variables x and y defined . Also it has two function. user1234 is the object of the class. If we want to access variable or function of the class then we have to prefix it with objectname. . Eg: in this case we have to say user1234.print_message(a); Also we need to note that we cant access x and y outside the body of class as they are private variables. Only functions of the class can use it. We can also define the body of a class function outside the class. We need to declare the function inside the class. Definiti on can be done outside class. // classes example #include <iostream> using namespace std; class ExamFear { int userId; public: void set_userId(int); }; void Examfear::set_userId (int x) { userId =x; } void main () { ExamFear ef; Ef.set_userId (1234); } Here we see that operator of scope ( :: ) is used to defined function of the class outside class.

Constructors and destructors In real world problems, we need to initialize variables during the process of creation based on business logic to avoid null values during exception. In order to achieve that we need special function called constructor. Constructor is automatically called when a new object is created. Then name of constructor should be same as class name and should not have any return type, not even void . // example of class constructor #include <iostream> class ExamFear { int userId; public: ExamFear (int); int showUserId() {return userId; } ExamFear:: ExamFear (int id) { userId = id; } void main () { ExamFear ef1(1234); Cout<< User id is :<< ef1.showUserId(); } The output is: User id is 1234 Here we see that while creating object (ef1) of class ExamFear, we passed the value of userId. The value 1234, is assigned to UserId. When we invoke showUserId, it displays the value 1234. Please note that constructors cannot be called explicitly as a regular member functions. They are only executed when a new object of that class is created. Also neither constructor declaration nor constructor definition has a return type. Destructor: The destructor does exactly opposite of constructor. It is used to destroy object of when. It is also automatically called by the system. Like constructor it also doesnt have any return type, but a destructor should precede with a tilde sign (~) . The use of

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

17

destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated. // example on constructors and destructors #include <iostream> class ExamFear { int *useId, *age; public: ExamFear (int,int); ~ExamFear (); int findAgeOfUser() {return (*age);} }; ExamFear::ExamFear (int a, int b) { useId = new int; age = new int; *useId = a; *age = b; } ExamFear::~ExamFear () { delete useId; delete age; } void main () { ExamFear ef1 (1234,24); cout << "Age of user is: " << ef1.findAgeOfUser() } Output: Age of user is 24 Overloading Constructors Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters. Remember that for overloaded functions the compiler will call the one whose parameters match the arguments used in the function call. In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed on the object declaration: Default constructor If you do not declare any constructors in a class definition, the compiler assumes the class to have a default constructor with no arguments. But as soon as you declare your own constructor for a class, the compiler no longer provides an implicit default constructor. So you have to declare all objects of that class according to the constructor prototypes you de fined for the class: Pointers to classes We can create a pointer that point to a class. Eg: ExamFear * ef; Here *ef is a pointer to calls ExamFear. In such case we need to use arrow operator () to refer members of class. Eg: ef userid = 10; // pointer to classes example #include <iostream> class AddNumber { int FirstNum, SecondNum; public: set_number(int , int); int SumOfNumbers {return (FirstNum + SecondNum);} }; void AddNumber::set_number (int a, int b) { FirstNum = a; SecondNum = b; } void main () { AddNumber a, *b, *c; AddNumber * d = new AddNumber[2]; b= new AddNumber; c= &a; a.set_number (3,5); b->set_number (1,6); d->set_number (2,7);

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

18

d[1].set_number (2,5); cout << "a SumOfNumbers: " << a.SumOfNumbers() << endl; cout << "*b SumOfNumbers: " << b->SumOfNumbers() << endl; cout << "*c SumOfNumbers: " << c->SumOfNumbers() << endl; cout << "d[0] SumOfNumbers: " << d[0].SumOfNumbers() << endl; cout << "d[1] SumOfNumbers: " << d[1].SumOfNumbers() << endl; delete[] d; delete b; } a SumOfNumbers: 8 *b SumOfNumbers: 7 *c SumOfNumbers: 8 d[0] SumOfNumbers: 9 d[1] SumOfNumbers: 7 Please read this example carefully. If you understand this example, then you understand the pointer. Lets focus on variablea first AddNumber a; a.set_number (3,5); cout << "a SumOfNumbers: " << a.SumOfNumbers() << endl; Here variable a is normal object of class AddNumber. Set number assigns value 3, 5 to FirstNum and SecondNum respectively. So the output of a.SumOfNumbers() is 3+5 = 8; Now lets focus on variable b; AddNumber *b; b= new AddNumber; b->set_number (1,6); cout << "*b SumOfNumbers: " << b->SumOfNumbers() << endl; delete b; Here *b is a pointer object of class Addnumber. So we called (b= new Addnumber) to allocate memory to it. Since *b is pointer , we access function of the class using and thus output is 1+6 =7; Since the memory was allocated explicitly, it has to be deleted explicitly and hence delete b is called. Now lets focus on variable c: AddNumber *c; c= &a; cout << "*c SumOfNumbers: " << c->SumOfNumbers() << endl; Here *c is also a pointer object of class Addnumber., but since it is pointer to object a, we need not allocate memory to it. c>SumOfNumbers() is same as a.SumOfNumbers(), and thus output is 3+5 =8; Now lets focus on variable d: AddNumber * d = new AddNumber[2]; d->set_number (2,7); d[1].set_number (2,5); cout << "d[0] SumOfNumbers: " << d[0].SumOfNumbers() << endl; cout << "d[1] SumOfNumbers: " << d[1].SumOfNumbers() << endl; delete[] d; Here *d is array of pointer to the class. Dset_number is same as d[0].set_number. The keyword this The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself.

Friendship and inhe ritance


Friend functions A friend function is used in object-oriented programming to allow access to private or protected data in a class from outside the class. Normally a function which is not a member of a class cannot access such information; neither can an external class. Occasionally such access will be advantageous for the programmer; under these circumstances, the function or external class can be

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

19

declared as a friend of the class using the friend keyword. The function or external class will then have access to all information public, private, or protected within the class. This procedure should be used with caution. If too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming. To declare an external function as friend of a class we just need to precede it with keyword friend. // friend functions #include <iostream> using namespace std; class ExamFear{ int numberOfUser,pageHit ; public: void setvalueUser(int); friend void setvalueHitC ount(int); }; void ExamFear::setvalueUser(int numUser); { numberOfUser = numUser; } void setvalueHitCount(int hitCount); { pageHit = hitCount; } Void main () { ExamFear ef1; ef1.setvalueUser(100); ef1.setvalueHitCount(5); } In this example we see that Examfear class has two function setvalueUser and setvalueHitCount, out of which setvalueHitCount is a friend function. That is why while defining the function we called it without preceding it with ExamFear :: . Note the diff erence in way setvalueHitCount and setvalueUser function is defined. Friend Classes: Just as we have we defined a friend function, we can also define a class as friend of another one. Doing so, we grant first c lass access to the protected and private members of the second one. Please note it is not other way round. Only First class can access protected and private members of the second one. Second class cant access protected and private members of the First one. Syntax; Class B; Class A { Friend Class B; } Here Class A is telling that Class B is its friend, but C lass B is not telling that C lass A is his friend. So C lass B can access ob jects of Class A. Example: Class B { int sumOfNumber(); }; Class A {int a1,a2; Friend C lass B; } int B:: sumOfNumber () { return a1+b1; } // Here method of class B i.e sumOfNumber is accessing objects of class A i.e a1,a2. Inheritance between classes

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

20

In real life we have scenarios were we want to create a class with some objects and functions and then inherit that class. Eg: If create a class called fourWheeler which has attributes like tyres, engine, body etc. Then we create class called car, bu s etc which has extra attributes such as AirConditioner, PowerWindow etc Classes that are derived from others inherit all the accessible members of the base class. That means that if a base class includes a member A and we derive it to another class with another member called B, the derived class will contain both members A and B. In order to derive a class from another, we use a colon (:) in the declaration of the derived class using the following format: class derived_class_name: public base_class_name { /*...*/ }; Where derived_class_name is the name of the derived class and base_class_name is the name of the class on which it is based. The public access specifier may be replaced by any one of the other access specifiers protected and private. This access specifier describes the minimum access level for the members that are inherited from the base class. #include <iostream> using namespace std; class FourWheeler { protected: int tyres_count, seat_count; public: void set_number (int a, int b) { tyres_count =a; seat_count = b; } } class Car: public FourWheeler { public: Boolean is_airConditioned; }; void main () { FourWheeler fw123; Car car123; fw123.set_number (4,6); car123.set_number (4,6); } The class car is inherited from class fourWheeler. Points to note in inheritance The access level public denotes the maximum access level for all members of inherited or derived class In case of protected access, all public members of base class are inherited are protected In case of private access, all members of base class are inherited are private If we dont specify access level then compiler assumes it as private

What is inherited from the base class? An inherited class inherits every member of a base class except: its constructor and its destructor its operator=() members its friends Multiple inheritance In real world, we have scenarios where a class is inherited from more than one class. We can do this in C++. This is done by simply separating the different base classes with commas in the derived class declaration. Class A: private B, private C; Here Class A is inherited from both Class B and C .

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

21

Pointe rs
A pointer is a variable that is used to store a memory address. The address is the location of the variable in the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space. Pointer points to a particular data type. The general form of declaring pointer is:type *variable_name; type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example, int *x; //x is the variable name and it is the pointer of type integer.

The computer memory is similar to a succession of memory cells each of size one byte. These memory cells are numbers in consecutive way. So if a block has address 1111 , then the cell is between memory location 1110 and 1112. Reference operator (&) The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example: int a = &b; Here a stores the address of b. Here if address of b is 1123, then a will store 1123. Dereference operator (*) We have just seen that a variable which stores a reference to another variable is called a pointer. Pointers are said to "point to" the variable whose reference they store. Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by". Therefore, following with the values of the previous example, if we write: int a = &b; Here a stores the address of b. Here if values of b is 10, then *a will be equal to 10. Notice the difference between the reference and dereference operators: & is the reference operator and can be read as "address of" is the dereference operator and can be read as "value pointed by" Declaring variables of pointer types Just as variable has its type, so is pointer. To declare a variable pqr we have to say either int pqr or any other <data_type> pqr; Similarly type of pointer depends on the data type it is pointing to. If a pointer is pointing to character, then it should b e declared as char *abc, similarly if it is pointing to integer, it should be declared as int * abc. Examples of pointer type: int * num1234; char * char123; float * floatingNumber; Please note that all these pointers will occupy same amount of memory. Pointers and arrays Array and pointers are linked. Array is a constant pointer. Lets declare an array int abc[10]; here abc denotes the memory location of first object of array abc[10]; If we say int *pqr; here pqr denotes the memory location too. The only difference is that w e can change the address of pqr by pointing it to another location, but we cant do so with array abc. Due to the characteristics of variables, all expressions that include pointers in the following example are perfectly valid: // more pointers #include <iostream> void main () { int num[5]; int * q; q = num; *q = 1; q++; *q = 2; q = &num[2]; *q = 3; q = num + 3; *q = 4;

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

22

q = num; *(q+4) = 5; for (int i=0; i<5; i++) cout << num[i] << ", "; } 1, 2, 3, 4, 5, Please look at this example carefully. Here we have declared an array of type int called num. Also we have declared a pointer of type int. 1. When we say q= num, then point q points to first block of num. Since q is now pointing to fist block, when we say *q=1, it is equivalent to num[0]=1; are *q is same as num[0]. 2. When we say q++, then q points to the next location. In this case q will now point to num[1]. Now when we say *q=2, it is same as numm[1]=2. 3. When we say q=&num[2]; we are pointing pointer to num[2] location. Thus *q now is same as num[2]. 4. When we say q = num+3, it means q should point to third location after num[0], that is q should point to q[3]. So *q is num[3] now. 5. When we say q = num, then point q points to first block of num. Now q = num[0]; If we say *(q+4) now, it means num[4] . Pointers to pointers C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in their declarations: int a; int * b; int ** c; a = 123; b = &a; c = &b; Here **c is pointer to pointer *b; Lets assume that addresss location of a is 100023; address location of b is 100034 and address location of c is 100044, then here is the values. Variable a b c Memory location 100023 100034 100044 Value stored 123 100023 100034

void pointers The void type of pointer is a special type of pointer that point to a value that has no type. This allows void pointers to point to any data type. But they cannot be de-referenced directly as there is no type associated with it. We a lways have to cast it before dereferencing it. Null pointer If a pointing is not pointing to anything it is called null pointer. Function Pointer: Function pointers do always point to a function having a specific signature. Thus, all functions used with the same function pointer must have the same parameters and return type. When de-referenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function. Eg: int * addition(int x, int y);

Abstract class

An abstract class is a class that is designed to be specifically used as a base class. It cannot be instantiated and is usual ly implemented as a class that has one or more pure virtual (abstract) functions. A pure virtual function can be declared by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration. The following is an example of an abstract class: class AB { public: virtual void f() = 0; // virtual function. }; An abstract class constitutes an incomplete type that is used as a foundation for derived classes. Although you cannot create objects of an abstract class , you can create pointers and references to an abstract class . This allows abstract classes to support runtime polymorphism, which relies upon base class pointers or references to select the proper virtual function . Polymorphism

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

23

Polymorphism enables one common interface for many implementations, and for objects to act differently under different circumstances. C++ supports several kinds of static (compile-time) and dynamic (run-time) polymorphisms. Compile-time polymorphism does not allow for certain run-time decisions, while run-time polymorphism typically incurs a performance penalty. Let us summarize: If an object A wishes object B to achieve some objective , it conveys this to object b by sending a message . The set of action taken by object B to achieve the end objective is called the method ;in other words , an object responds to a message using a method . Different objects may use different methods in response to the same message. The term polymorphism has been derived from greek words poly and morphos which means many and forms respectively . Polymorphism broadly divided in two types: Static polymorphism exhibited by overloaded functions. Dynamic polymorphism exhibited by using late binding. Static Polymorphism Static polymorphism refers to an entity existing in different physical forms simultaneously. Static polymorphism involves bin ding of functions based on the number, type, and sequence of arguments. The various types of parameters are specified in the function declaration, and therefore the function can be bound to calls at compile time. This form of association is called early bindi ng. The term early binding stems from the fact that when the program is executed, the calls are already bound to the appropriate functions. The resolution of a function call is based on number, type, and sequence of arguments declared for each form of the function. Consider the following function declaration: void add(int , int); void add(float, float); When the add() function is invoked, the parameters passed to it will determine which version of the function will be executed . This resolution is done at compile time. Dynamic Polymorphism Dynamic polymorphism refers to an entity changing its form depending on the circumstances. A function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program i s executed. The term late binding refers to the resolution of the functions at run-time instead of compile time. This feature increases the flexibility of the program by allowing the appropriate method to be invoked, depending on the context. Static Vs Dynamic Polymorphism Static polymorphism is considered more efficient, and dynamic polymorphism more flexible. Statically bound methods are those methods that are bound to their calls at compile time. Dynamic function calls are bound to the functions during run-time. This involves the additional step of searching the functions during run-time. On the other hand, no runtime search is required for statically bound functions. As applications are becoming larger and more complicated, the need for flexibility is increasing rapidly. Most users have to periodically upgrade their software, and this could become a very tedious task if static polymorphism is applied. This is because any change in requirements requires a major modification in the code. In the case of dynamic binding, the function calls are resolved at run-time, thereby giving the user the flexibility to alter the call without having to modify the code. To the programmer, efficiency and performance would probably be a primary concern, but to the user, flexibility or maintainab ility may be much more important. The decision is thus a trade-off between efficiency and flexibility. Exception handling An exception can be defined as an unexpected event that occurs during the execution of a program and disrupts the normal of instructions. The exception- handling facility of c++ allows programs to handle abnormal and unexpected situations in a structured and orderly manner . C++ reacts in the following ways when an exception occurs: The function in which the exception has occurred may generate a system defined message. The function may terminate completely . The function may skip the intermediate levels and proceed to another section . There can be three types of outcomes when a function is called during program execution . these are Normal execution Erroneous execution Abnormal execution . When a function detects an exceptional situation, you represent this with an object. This object is called an exception objec t. In order to deal with the exceptional situation you throw the exceptio n. This passes control, as well as the exception, to a designated block of code in a direct or indirect caller of the function that threw the exception. This block of code is called a handler. In a handler, you specify the types of exceptions that it may process. The C++ run time, together with the generated code, will pass control to the first appropriate handler that is able to process the exception thrown. When this happens, an exception is caught. A handler may rethrow an exception so it can be caught by another handler. The exception handling mechanism is made up of the following elements: try blocks catch blocks

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

24

throw expressions Exception specific NameSpace: The purpose of namespaces is to localize the name of identifiers to avoid name collisions, the c++ environment has seen an explosion of variable , function and class name. Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. The format of namespaces is: namespace identifier { entities } Where identifier is any valid identifier and entities is the set of classes, objects and functions that a re included within the namespace. For example: namespace myNamespace { int a, b; } In this case, the variables a and b are normal variables declared within a namespace called myNamespace. In order to access t hese variables from outside the myNamespace namespace we have to use the scope operator ::. For example, to access the previous variables from outside myNamespace we can write: myNamespace::a myNamespace::b A name within a namespace can be referred in two ways : Using the scope resolution operator . Better solution comes in the form of using keywords . The using keywords declares all the names in the namespaces to be in the current scope, and can be used without qualification . Using one namespaces does not override another . when you bring a namespace into view , it simply adds its names to whatever other namespaces are currently in effects . Type Casting Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast: Implicit conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible typ e. For example: short a=2000; int b; b=a; Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion. Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example: class A {}; class B { public: B (A a) {} }; A a; B b=a; Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed. Explicit conversion C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c -like casting: short a=2000; int b; b = (int) a; // c-like cast notation b = int (a); // functional notation

Visit ExamFear.com for Free Question Papers for almost all Exams.

Page

25

Das könnte Ihnen auch gefallen