You are on page 1of 25


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




Input /output




Visit for Free Question Papers for almost all Exams.




Default constructor Inheritance Friendship Multiple Inheritacne


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


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 don‘t 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 let‘s understand the code we have written: // my first hello India program in C++

Visit for Free Question Papers for almost all Exams.



and you will receive an error message informing you that you have made a for Free Question Papers for almost all Exams. Case Sensitivity: Now is a good time to talk about an important concept that can easily throw you off: case sensitivity. Declaring Variables in C++ To declare a variable you use the syntax "type <name>. known as line comment. all functions and all variables are case sensitive. int. #include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor. Each of these variable types . and variables of type float store numbers with decimal places. 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). cout is declared in the iostream standard file within the std namespace. // line comment 2. float cost_price. Undeclared variable: If you attempt to use a variable that you have not declared. Why so many variable types? We use so many variable types to make your code efficient and readable. Page 3 . This line is a C++ statement. and float .h file. Basically. cout << "Hello India". All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The words Cat and cat mean different things to the compiler. /* block comment */ The first of them. A difference in case between your variable declaration and the use of the variable is one reason you might get an undeclared variable error. char student_name. This specific file (iostream) includes the declarations of the basic standard input-output library in C++. In this case the directive #include <iostream> tells the preprocessor to include the iostream header file. The second one. Common Errors when Declaring Variables in C++ 1. 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). Using the right variable type can be important for ma king your code readable and for efficiency--some variables require more memory than others.: Char should not be used to store number. Float should be used only if you want to store decimal. void main () This line corresponds to the beginning of the definition of the main function. variables of type int store integers (numbers without decimal places).). The main function is the point by where all C++ programs start their execution. We will use more includes in our future programs.char. with the possibility of including more than one line. They simply do nothing. Notice that the statement ends with a semicolon character (. in C ++. The programmer can use them to include short explanations or observations within the source code its elf.g. whether you use uppercase or lowercase letters matters. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. Why variables? Variables are used to store values that can be used by program.This is a comment line. A variable of type char stores a single each a keyword that you use when you declare a variable. Visit ExamFear. 2. independently of its location within the source code. They are not regular code lines with expressions but indications for the compiler's preprocessor. In C++.". Comments Comments are parts of the source code disregarded by the compiler. In this case. It is essential that all C++ programs have a main function. E. cout represents the standard output stream in C++. Here are some variable declaration examples: int x. known as block comment. Here cout function is defined in iostream. The word main is followed in the code by a pair of parentheses (()). discards everything from where the pair of slash signs ( //) is found up to the end of that same line. all language keywords. this is called an undeclared variable. Usually. C++ supports two ways to insert comments: 1. the line is a brief description of what our program is. and it is included because its functionality is going to be used later in the program. Also it is used to pass value from user to computer. 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. discards everything between the /* characters and the first appearance of the */ characters. your program will not be compiled or run.

float. and_eq. volatile. Identifiers A valid identifier is a sequence of one or more letters. delete. Character Type The character type is used to store characters . Int result = a + b. xor. sizeof. We can declare signed and unsigned characters. false. 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. for. double. such as a whole number or a character. Neither spaces nor punctuation marks or symbols can be part of an identifier. A char is guaranteed to be at least 8 bits in size. bitor. 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. whenever it is after its declaration. Only letters. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. enum. extern. we have to tell the compiler which type of data we want to store. try. where signed characters can have positive and negative values. unsigned or plain integer values as follows: Visit ExamFear. We can use signed. using. compl. Using Variables Ok. digits and single underscore characters are valid. const. bool. Boolean Type The Boolean type can have the value true or false. while Some operators cannot be used as identifiers since they are reserved words under some circumstances: and. each one should be separated by a comma. pr ivate. Fundamental data types When we wish to store data in a C++ program. dynamic_cast. virtual. Rules for identifiers: 1. if. typename. unsigned. or. so you now know how to tell the compiler about variables. integer and floating-point. c. For example: bool flag = false. int a. inline. while a local variable is one declared within the body of a function or a block. even inside functions. static. Identifiers are case sensitive. Global variables can be referred from anywhere in the code. static_cast. else. which are reserved keywords. namespace. throw. new. 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). break. or_eq. switch. friend. not_eq. but what about us ing them? One application of variable is an addition program. struct. and unsigned characters can only contain positive values. auto. template. Int b = 3. const_cast. If you were watching closely. in that case you have to put number1 and number2 in memory and then add it. Int a = 6. class. continue. char number = '52'. default. char. digits or underscore characters (_). The standard reserved keywords are: asm. Page 4 . Identifiers cannot match any keyword of the C ++ language nor your compiler's specific ones. b. In no case can they begin with a digit. union. true. A global variable is a variable declared i n the main body of the source code. case. Integer Types The integer type is used for storing whole numbers. In such case you will need variable. Variable identifiers always have to begin with a letter or an underline character (_ ). return. protected.It is permissible to declare multiple variables of the same type on the same line. goto. short. catch. bitand. wchar_t. mutable. typedef. export. d. typeid. xor_eq Local and Global Variables A variable can be either of global or local scope. void. character. for Free Question Papers for almost all Exams. For example: char alphabet = 'a'. int. Fundamental types C++ provides the following fundamental built-in data types: Boolean.typically ASCII characters but not always. long. explicit. 3. register. do. reinterpret_cast. 6. If a Boolean value is converted to an integer value true becomes 1 and false becomes 0 and vice versa. 4. 5. signed. Suppose you want to add two numbers. not. operator. public. outside all functions.

Floating point number. Here is an example of a struct declaration: struct Student { char strName[20]. To do this. address. phone number etc. to represent student.signed int marks = -187. bool float double long double wchar_t 4bytes Boolean value. class.087. Page 5 . 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 +/. double fahrenheit = 98. int age. For example.23. A short integer is guaranteed to be at least 16 bits and a long integer at least 32 bits.38 (~7 digits) +/. Furthermore.Char address[50]. Name char short int (short) int Description Character or small integer.415. they're always signed. Like characters. However. int population = 998100. or any other number of characteristics about student. double (double-precision) and long double (extended-precision). for example 1. float (single-precision). The range of values for these types will be defined by your for Free Question Papers for almost all Exams. Examples of composite data types are enum. Short Integer. plain integer can always hold positive or negative values. Integer.1.4e +/. Some examples: float celsius = 37. C++ allows us to create our own user-defined aggregate data types. Visit ExamFear.308 (~15 digits) +/. A struct (short for structure) allows us to group variables of mixed data types together into a single unit. If you wanted to pass information about yourse lf to a function. if you wanted to store information about more people. we first have to tell the compiler what our struct looks like before we can begin using it. long double accountBalance = 1897. Because structs are user-defined. Wide character.7e +/. 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. you now have 4 independent variables that are not grouped in any way. short int and long int. -. One of the simplest aggregate data type is the struct.623.1. you‘d have to declare 4 more variables for each additional student. Floating-Point Types Floating point types can contain decimal numbers. Fortunately. You could do so like this: char strName[20]. struct. 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. However.308 (~15 digits) 1 wide character long int (long) Long integer.23. string etc Structs or Structures There are many instances in programming where we need more than one variable in order to represent something. Long double precision floating point number. you‘d have to pass each variable individually.7e +/. age. The range of values that can be stored in each of these is defined by your compiler . plain int. It can take one of two values: true or 1byte false. unsigned int vote = 12. int age. int phoneNumber. and unsigned integers can hold only positive values. Integer values come in three sizes. we declare our struct using the struct keyword. signed integers can hold positive or negative values. you might want to store name. Double precision floating point number. An aggregate data type is a data type that groups multiple individual variables together. There are three sizes.

arrayStudentId[0]= 123. The Employee struct contains 4 variables inside of it: t wo ints and two char. the first enumerator is assign ed the integer value 0. These variables are called members (or fields). When a variable of the enumerated type is declared memory is allocated for that variable at that time.. with a unique identifier. 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. = 3. Let‘s look at an example: enum Color_list {C OLOR_BLACK. // this is array of length 5. This is because each enumerator is automatically assigned an integer value based on it‘s position in the enumeration list. That means that. arrayStudentId[1]= 124. Using this command we create objects of student .com for Free Question Papers for almost all Exams. = 4. for example. Int phoneNumber. It is represented internally as: 0 0 1 2 1 2 3 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). Instead of that. using an array we can store 5 different values of the same type. Enum variables are the same size as an int variable. Defining an enumerated type does not allocate any memory.. This can store 10 student ids. we can store 10 values of type int in an array without having to declare 10 different variables.Char address. S1 and S1 and hence memory is allocated. no memory is allocated at this time. By default. = 5. COLOR_BLUE}. In order to use the Employee struct. s2.2. } This tells the compiler that we are defining a struct named Student. Enumerated types are declared via the enum keyword.5}.4. = 2. int int int int int int employeeId[5] employeeId[0] employeeId[1] employeeId[2] employeeId[3] employeeId[4] = { 1. Keep in mind that the above is just a declaration — even though we are telling the compiler that the struct will have variables. Multi Dimensional array: int ExamFear[3][4]. COLOR_RED. Int arrayStudentId[10]. int for example. etc. each one with a different identifier. we simply declare a variable of type Employee: Student s1. 6 . and each subsequent Page Visit ExamFear.3. and it is similar to = 1.

team_count and team_name are two typed constants. Arithmetic operators ( +.enumerator has a value one greater than the previous enumerator: Typedefs Typedefs allow the programmer to create an alias for a data type. // define StudentId as an alias for int // The following two statements are equivalent: Int CollegeStudentId. const char team_name = 'India'.com for Free Question Papers for almost all Exams. /. Operators Operator is used to operate variables and constants. member_type3 member_name3. followed by the alias name . but is just another name for an existing type. We cannot store different values in them independent of each other. . -. This statement assigns the integer value 10 to the variable i. since all of them are in fact the same location in memory.8 This defines a new constant: Rupee_dollar_conversion. simply by using the #define preprocessor directive. followed by the type to alias. Defined constants (#define) You can define your own names for constants that you use very often without having to resort to memory consuming variables. Its format is: #define identifier value For example: #define Rupee_dollar_conversion 43. simply use the typedef keyword. StudentId CollegeStudentId. % ) The five arithmetical operations supported by the C ++ langua ge are: + addition . member_type2 member_name2. Page 7 . Its size is the one of the greatest element of the declaration. typedef int StudentId. Here.g : int i = 10. E. T o declare a typedef. and use the aliased name instead of the actual type name. . Assignment (=) This operator assigns a value to a variable. } object_names. you can use it in the rest of the code as if they were any other regular constant. the modification of one of the elements will affect the value of all of them. A typedef can be used anywhere a regular type can be used. All the elements of the union declaration occupy the same physical space 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. The assignment operation always takes place from right to left only. Typedefs are used mainly for documentation and legibility purposes.subtraction Visit ExamFear. Lets discuss various kinds of operators in C++. Since all of them are referring to the same location in memory. A typedef does not define new type. Unions Unions allow one same portion of memory to be accessed as different data types. They are treated just like regular variables except that their values cannot be modified after their definition. 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. *. The part at the left of the assignment operator (=) is variable whereas the one on right is constant. Once it is defined.

if both A and B are true.b=b-1. p = p . //Here R stores 5 and P stores 6. &=. (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. Page 8 . result is false. 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. a = a * (b -5). When the set of expressions has to be evaluated for a value. the following code: p = (q=4. P=5. a *= b . result is true. |=) 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. q+3). <<=. It is false only when both A and B are false. (5<2) // this returns false. For A && B. Usage Example: p -= 6. For A && B. --) Increase operator (++) and the decrease operator (--) increase or decrease by one the value stored in a variable. (2>5) // this returns false. *=. -=. For example. the variable a will contain the value 2. Let‘s see the example to clarify any doubts if any. Its format is: variable = condition ? result1 : result2 If condition is true the expression will return result1. p /=q. Visit ExamFear. a=a+1. R = P++. Increase and decrease (++. ^=. >>=. Even if one is false. are all same. For example. if it is not it will return result2.) is used to separate two or more expressions that are included where only one expression is expected. Comma operator ( .a+=1. == Equal to != Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to Let‘s see some examples to clarify doubts if any. since 9 is not greater than 5. All increase value of a by 1. %=. multiplication and division literally correspond with their respective mathematical operators. Q= ++P. result is true else it is false. /=. Modulo is the operation that gives the remainder of a division of two values. since 2 is the remainder from dividing 10 by 4. A = 9<5 ? 5 : 6 // returns 6. only the rightmost expression is considered. p = p / q. if we write: int b = 10 % 4. //Here both P and Q stores 6.5. (5!= 5) // this returns false. subtraction. are all same. Compound assignment (+=. P=5. || Operator: This is logical OR operator. ) The comma operator (.b-=1. 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. Relation and equality operator: Relational and equality operators are used to compare between two for Free Question Papers for almost all Exams. (5== 2) // this returns false. b--. a++ . even if either of A or B is true.6. The result of a relational operation is a Boolean value that can only be true or false.* multiplication / division % modulo Operations of addition.

The first statement declares a variable of type int called age. The value returned by sizeof is a constant. int integer_value =0. here integer_value stores values 5 as decimal place is lost in type conversion. jump to code in some other place. cout is used in conjunction with the insertion operator. we need scenarios where program need to take decision. and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. the standard output of a program is the screen. A stream is an object where a program can either insert or extract characters to/from it. float c. " << "I am " << "a C++ statement". Input/Output in C++ C++ uses streams to perform input and output for Free Question Papers for almost all Exams. Block is a group of sentence that are enclosed in {}. Standard Output (cout) By default. This is done by writing by the new type enclosed between parentheses (()): float float_vlaue = 5. This will assign the value 1 to a because char is a one-byte long type. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. repeat code etc.Here q is assigned 4 in first place. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. even if you request a single character. then q+3. char b. Before we proceed further. cout << "Hello". sizeof() This operator accepts one parameter. and the C++ stream object defined to access it is cout. Therefore. cin can only process the input from the keyboard once the RETURN key has been pressed. Standard Input (cin).} if and else The if keyword is used to execute a piece of statement or block only when a given condition is true. Eg: { int a. so it is always determined before program execution. cin >> age. This can‘t be achieved by linear sequence of instructions. Control Structures In real world. // prints Hello cout << Hello. Syntax: If ( condition) { Execute this block if condition is true} else Page Visit ExamFear.234. which is written as << (two "less than" signs). Else statement is used to execute a piece of statement or block only when a given statement is false. // prints the content of Hello variable The insertion operator (<<) may be used more than once in a single statement: cout << "Hello. let me introduce you to a concept called block. Type casting can also be done in the syntax mentioned below.h defines methods for input output using streams. It is important to notice that cout does not add a line break after its output unless we explicitly indicate it. The standard input device is usually the keyboard. integer_value = (int) float_vlaue. the extraction from cin will not process the input until the user presses RETURN after the character has been introduced. So we have concept of control structures. 9 . that is (4+3 =7) is assigned to P. Header file iostream. Explicit type casting operator Type casting operators are used to convert a variable from on type to another type. integer_value = int (float_value ). The above code converts float float_vlaue to int. which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char). For example: int age.

the cout statement will be executed only once. int ―. } This will execute infinite number of times. Syntax: do {statements to be executed} while (condition). this loop will print infinite times. } while (i ==5) This statement will be executed once even when the condition is false int ―. do { count<<‖ this is a tutorial by‖. While(true) {count<<‖ this is a tutorial by examfear. } Without break statement. This is because condition in the do-while loop is evaluated after the execution of statement instead of before. } This statement will not be executed even once. While(i>0) { count<<‖ this is a tutorial by examfear. 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. but sine we have placed a break for Free Question Papers for almost all Exams. The continue statement Visit ExamFear. Page 10 . while(true) { cout<<‖ this document is brought to you by ―.{ 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. Int i=10. ―. the statements will be executed till the condition is true. Format: while (Condition is true) { statements to be executed } In this case. while (i ==5 { count<<‖ this is a tutorial by examfear. i--. } This statement will be executed 10 times. The break statement Break statement is used to come out of a loop evein if condition is not fulfilled.

Label1234: } // if the number is even. cout<< i. then we can use continue statement to skip printing of even number. Page 11 . break. 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‖. default: default group of statements } Working of switch statement: 1. The goto statement goto statement is used when we want to jump to another point in the program. It should be some constant. case 2: cout << "a is 2‖. 4. Suppose we want to print odd numbers from 1 to 10. while ( i <10) {i++. break.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. ―a is 3‖ if a==3 and ―a is unknown‖ if a is any other number. break. . . Visit ExamFear.s if(i%2 == 0) Label1234. Switch statement. It executes the statement till it encounters a break statement. break. default: cout << "a is unknown". Please note the break statement. Syntax: void exit (int exitcode). switch (expression) { case constant1: group of statements 1. case 3: cout << "a is 3‖. That is why block is not needed in s witch. Based on the value it goes to case <<value of expresion>> statement 3. Suppose we want to print odd numbers from 1 to 10. cout<< i. which is then used as an argument for the goto statement. int i = 0. if(i%2 == 0) continue. then we can use continue statement to skip printing of even number. while ( i <10) {i++. By convention. A label is made of a valid identifier followed by a colon (:). The destination point is identified by a label. . ―a is 2‖ if a==2. } This code will print ―a is 1‖ is a ==1. 2. exit is a function defined in the cstdlib library . It evaluates for Free Question Papers for almost all Exams. case constant2: group of statements 2. The exit function The purpose of exit is to terminate the current program with a specific exit code. The exitcode is used by some operating systems and may be used by calling programs. it will return true and hence we will to label1234. an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened. int i = 0. break. it will return true and hence we will skip the next statement. } // if the number is even. 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.

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

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

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

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

Visit ExamFear. 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).// to allocate memory containing one single element of type ―type‖. Operators delete and delete[] To delete the memory not in use. 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. It is to be decided run time. Here system allocates space for 3 elements of type int and return a pointer to the first element. but also from derived classes. 2. In terms of variables. } object_nm. Function definition : Eg: int additionFx(int a. We will talk about friendslater. Syntax: delete pointer. In real world. Classes A class is an expanded concept of a data structure: instead of holding only data. delete operator is used. public or protected.Let‘s revise what all we can do with function. int b){ return (a+b).. //to allocate memory containing ―n‖ number of elements of type ―type‖.. The value passed as argument to delete must be either a pointer to a memory block previously allocated with new. . we sometimes are not aware of the size of variable at the time of coding. The first expression should be used to delete memory allocated for a single element. etc System memory heap is allocated to the dynamic memory items and we know that system has limited memory resource. Eg: int i. Access_specifier are keywords private. Since we don‘t know then number of user. Things we can do with function: 1. Function invocation/call: Eg: int p =additionFx( for Free Question Papers for almost all Exams.. a class would be the type.2). and an object would be the variable. Function declaration: Eg int additionFx(int. with the following format: class class_nm { access_specifier_a: member1. we will have to allocate memory dynamically. and the second one for memory allocated for arrays of elements. Page 16 . An object is an instantiation of a class. ExamFear = new int [3]. so it is advisable to delete or free the resource not in use. etc. object_nm is name of object. it can hold both data and functions. Operators new and new[] ―new‖ operator is used to dynamically allocate memory. Classes are generally declared using the keyword class. delete [] 3. Protected members are accessible not only from members of same class and friends.} 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. access_specifier_b: member2. int b[5]. function(parameters). Here Class_nm is unique name of class. Public members are accessible from anywhere where object is visible. If no access specifier is defined then it is considered private. 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. Eg: we want to store the details of users who has visited a website on a particular day. In such scenarios we need to use dynamic memory.

We need to declare the function inside the class.set_userId (1234).//Example of class class ExamFear { int x. ― . } void main () { ExamFear ef.print_message(―a‖). } The output is: User id is 1234 Here we see that while creating object (ef1) of class ExamFear. public: void print_message(char). void Examfear::set_userId (int x) { userId =x. We can also define the body of a class function outside the class. Then name of constructor should be same as class name and should not have any return type. Constructors and destructors In real world problems. The value 1234. // example of class constructor #include <iostream> class ExamFear { int userId. we need to initialize variables during the process of creation based on business logic to avoid null values during exception. The above code defines a class called Examfear which has two variables x and y defined . It is also automatically called by the system. public: void set_userId(int). public: ExamFear (int). If we want to access variable or function of the class then we have to prefix it with ―objectname. ―user1234‖ is the object of the class. The use of Visit ExamFear. not even void . Page 17 . int showUserId() {return userId. but a destructor should precede with a tilde sign (~) . Constructor is automatically called when a new object is created. It is used to destroy object of for Free Question Papers for almost all Exams. Like constructor it also doesn‘t have any return type. When we invoke showUserId. int user_id (char). Cout<<‖ User id is :‖<< ef1. Destructor: The destructor does exactly opposite of constructor. } ExamFear:: ExamFear (int id) { userId = id. class ExamFear { int userId. Definiti on can be done outside class. it displays the value 1234.showUserId(). They are only executed when a new object of that class is created. Also we need to note that we can‘t access x and y outside the body of class as they are private variables. Eg: in this case we have to say user1234. Only functions of the class can use it. }. y. } void main () { ExamFear ef1(1234). Please note that constructors cannot be called explicitly as a regular member functions. Also neither constructor declaration nor constructor definition has a return type. Also it has two function. } Here we see that operator of scope ( :: ) is used to defined function of the class outside class. Ef. } user1234. we passed the value of userId. // classes example #include <iostream> using namespace std. is assigned to UserId. In order to achieve that we need special function called constructor.

// example on constructors and destructors #include <iostream> class ExamFear { int *useId. *useId = a. b= new AddNumber. int findAgeOfUser() {return (*age). In the case of constructors. Here *ef is a pointer to calls ExamFear. public: set_number(int .} }. d->set_number (2. cout << "Age of user is: " << ef1.5).com for Free Question Papers for almost all Exams. public: ExamFear (int.24). SecondNum = b.findAgeOfUser() } Output: Age of user is 24 Overloading Constructors Like any other function. Visit ExamFear. Eg: ef  userid = 10. SecondNum. // pointer to classes example #include <iostream> class AddNumber { int FirstNum. ~ExamFear (). } void main () { ExamFear ef1 (1234. In such case we need to use arrow operator () to refer members of class. the compiler assumes the class to have a default constructor with no arguments. 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. *c. which are automatically called when an object is created. ExamFear::ExamFear (int a. Remember that for overloaded functions the compiler will call the one whose parameters match the arguments used in the function call. Page 18 . int). the compiler no longer provides an implicit default constructor. * delete age.} }.set_number (3. } void main () { AddNumber a. a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters. int b) { useId = new int. age = new int. } ExamFear::~ExamFear () { delete useId.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. c= &a. int SumOfNumbers {return (FirstNum + SecondNum). But as soon as you declare your own constructor for a class. Eg: ExamFear * ef. a. void AddNumber::set_number (int a. *age.7). *age = b. b->set_number (1. int b) { FirstNum = a. 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.6). AddNumber * d = new AddNumber[2].

SumOfNumbers() << endl.set_number (2. 5 to FirstNum and SecondNum respectively. Now lets focus on variable “b”.d[1]. d[1]. c= &a.SumOfNumbers() << endl.SumOfNumbers() is 3+5 = 8.set_number. a. but since it is pointer to object a. Occasionally such access will be advantageous for the programmer. cout << "a SumOfNumbers: " << a.SumOfNumbers() << endl. Now lets focus on variable “c”: AddNumber *c. Normally a function which is not a member of a class cannot access such information. } a SumOfNumbers: 8 *b SumOfNumbers: 7 *c SumOfNumbers: 8 d[0] SumOfNumbers: 9 d[1] SumOfNumbers: 7 Please read this example carefully. b->set_number (1. we need not allocate memory to it. Page 19 . cout << "d[0] SumOfNumbers: " << d[0]. Here *d is array of pointer to the class.SumOfNumbers().5). It is a pointer to the object itself. So we called (b= new Addnumber) to allocate memory to it. cout << "*b SumOfNumbers: " << b->SumOfNumbers() << endl.SumOfNumbers() << endl.set_number (2. cout << "d[1] SumOfNumbers: " << d[1].SumOfNumbers() << endl. Since the memory was allocated explicitly. So the output of a. Lets focus on variable”a” first AddNumber a. delete b.5). cout << "a SumOfNumbers: " << a. If you understand this example. cout << "*b SumOfNumbers: " << b->SumOfNumbers() << endl.7). Here *b is a pointer object of class Addnumber. Here *c is also a pointer object of class Addnumber. under these circumstances.6). Now lets focus on variable “d”: AddNumber * d = new AddNumber[2]. The keyword this The keyword this represents a pointer to the object whose member function is being executed. Here variable ―a‖ is normal object of class AddNumber. neither can an external class.SumOfNumbers() << endl. c>SumOfNumbers() is same as a. delete b. it has to be deleted explicitly and hence delete b is called.set_number (3. 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. delete[] for Free Question Papers for almost all Exams. Since *b is pointer . we access function of the class using  and thus output is 1+6 =7. b= new AddNumber. cout << "*c SumOfNumbers: " << c->SumOfNumbers() << endl. cout << "d[0] SumOfNumbers: " << d[0]. delete[] d. AddNumber *b. Dset_number is same as d[0]. Set number assigns value 3. the function or external class can be Visit ExamFear. cout << "d[1] SumOfNumbers: " << d[1].5). then you understand the pointer. and thus output is 3+5 =8. cout << "*c SumOfNumbers: " << c->SumOfNumbers() << endl. d->set_number (2..

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

set_number (4. Visit ExamFear. ―bu s‖ etc which has extra attributes such as AirConditioner. engine. 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. } The class car is inherited from class fourWheeler. fw123. Here Class A is inherited from both Class B and C . class FourWheeler { protected: int tyres_count. Car car123. private C.. all public members of base class are inherited are protected In case of private access. That means that if a base class includes a member A and we derive it to another class with another member called B.set_number (4. Page 21 . In order to derive a class from another. int b) { tyres_count =a. PowerWindow etc Classes that are derived from others inherit all the accessible members of the base class. Eg: If create a class called ―fourWheeler‖ which has attributes like tyres. seat_count. This is done by simply separating the different base classes with commas in the derived class declaration. }.In real life we have scenarios were we want to create a class with some objects and functions and then inherit that class. seat_count = b. Then we create class called ―car‖. the derived class will contain both members A and B.6). } } class Car: public FourWheeler { public: Boolean is_airConditioned. we have scenarios where a class is inherited from more than one class. Class A: private for Free Question Papers for almost all Exams. car123. 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. all members of base class are inherited are private If we don‘t 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. public: void set_number (int a..*/ }.6). we use a colon (:) in the declaration of the derived class using the following format: class derived_class_name: public base_class_name { /*. void main () { FourWheeler fw123. This access specifier describes the minimum access level for the members that are inherited from the base class. body etc. The public access specifier may be replaced by any one of the other access specifiers protected and private. We can do this in C++. #include <iostream> using namespace std.

here ―abc‖ denotes the memory location of first object of array abc[10]. Pointers improve execution time and saves space. but we can‘t do so with array abc. To do this. Please note that all these pointers will occupy same amount of memory. here pqr denotes the memory location too. known as reference operator. The computer memory is similar to a succession of memory cells each of size one byte. *q = 3. following with the values of the previous example. *q = 1.Pointe rs A pointer is a variable that is used to store a memory address. then the cell is between memory location 1110 and 1112. Similarly type of pointer depends on the data type it is pointing to. which acts as dereference operator and that can be literally translated to "value pointed by". These memory cells are numbers in consecutive way. char * char123. //x is the variable name and it is the pointer of type integer. float * floatingNumber. then it should b e declared as char *abc. Examples of pointer type: int * num1234. Visit ExamFear. if we write: int a = &b. similarly if it is pointing to integer. Pointers and arrays Array and pointers are linked. To declare a variable ―pqr‖ we have to say either int pqr or any other <data_type> pqr. Here if values of b is 10. *q = 4. Due to the characteristics of variables. For example: int a = &b. q++. so is pointer. Pointers are said to "point to" the variable whose reference they store. So if a block has address 1111 . we simply have to precede the pointer's identifier with an asterisk (*). For example. q = num. If we say int *pqr. Page 22 . Here if address of b is 1123. The general form of declaring pointer is:type *variable_name. all expressions that include pointers in the following example are perfectly valid: // more pointers #include <iostream> void main () { int num[5]. The only difference is that w e can change the address of pqr by pointing it to another location. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&). and which can be literally translated as "address of". Array is a constant pointer. 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. Pointers help in allocating memory dynamically. then *a will be equal to 10. *q = 2. it should be declared as int * abc. Therefore. type is the base type of the pointer and variable_name is the name of the variable of the pointer. Lets declare an array int abc[10]. Pointer points to a particular data type. The address is the location of the variable in the memory. Using a pointer we can directly access the value stored in the variable which it points for Free Question Papers for almost all Exams. int * q. q = &num[2]. then a will store 1123. int *x. Here ―a‖ stores the address of ―b‖. If a pointer is pointing to character. Here ―a‖ stores the address of ―b‖. q = num + 3. Reference operator (&) The address that locates a variable within memory is what we call a reference to that variable. Dereference operator (*) We have just seen that a variable which stores a reference to another variable is called a pointer.

2. are *q is same as num[0]. Thus. that these. then q points to the next location. In order to do that. it means num[4] . Since q is now pointing to fist block. it means q should point to third location after num[0]. In this case q will now point to num[1]. ". 3. When we say q = num+3. c = &b. Now when we say *q=2. b = &a. Polymorphism Visit ExamFear. Here **c is pointer to pointer *b. When we say q++. When we say q = num. We a lways have to cast it before dereferencing it. When we say q= num. // virtual function. when we say *q=1. then point q points to first block of num.q = num. Function Pointer: Function pointers do always point to a function having a specific signature. we only need to add an asterisk (*) for each level of reference in their declarations: int a. Thus *q now is same as num[2]. point to data (or even to other pointers). Abstract class An abstract class is a class that is designed to be specifically used as a base class. for (int i=0. address location of b is 100034 and address location of c is 100044. So *q is num[3] now. Here we have declared an array of type int called num. *(q+4) = 5. Eg: int * addition(int x. If we say *(q+4) now. Please look at this example carefully. we are pointing pointer to num[2] location. }. Although you cannot create objects of an abstract class . then here is the values. Null pointer If a pointing is not pointing to anything it is called null pointer. a function pointer can be used to invoke a function and pass it arguments just like a normal function. An abstract class constitutes an incomplete type that is used as a foundation for derived classes. int ** c. 5. This allows abstract classes to support runtime polymorphism. Lets assume that addresss location of a is 100023. i<5. 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. This allows void pointers to point to any data type. 4. a = 123. It cannot be instantiated and is usual ly implemented as a class that has one or more pure virtual (abstract) functions. 1. which relies upon base class pointers or references to select the proper virtual function . all functions used with the same function pointer must have the same parameters and return type. But they cannot be de-referenced directly as there is no type associated with it. Page 23 . i++) cout << num[i] << ". Also we have declared a pointer of type int. it is equivalent to num[0] for Free Question Papers for almost all Exams. When we say q=&num[2]. The following is an example of an abstract class: class AB { public: virtual void f() = 0. When de-referenced. int y). 2. } 1. Pointers to pointers C++ allows the use of pointers that point to pointers. int * b. Now q = num[0]. 4. 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. it is same as numm[1]=2. you can create pointers and references to an abstract class . 5. 3. in its turn. then point q points to first block of num. that is q should point to q[3].

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

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