Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 28

Name : Bhavin M Shah Roll No : 45

Object Oriented Programming Structure


Class Assignment No. 1
Q.1) What are manipulators? Explain various types of manipulators in C++? Explain it with suitable example? Ans. Manipulators: Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects. They are still regular functions and can also be called as any other function using a stream object as argument. Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters. It just changes certain characteristics of the input and output. There are several manipulators in C++. It includes: endl - Ends the line and calls flush. ends - Inserts '\0' ( NULL) into the stream. flush - Force the buffer to be output immediately. boolalpha - Insert or extract bool objects as "true" or "false". noboolalpha - Insert or extract bool objects as numeric values. fixed - Insert floating-point values in fixed format. scientific - Insert floating-point values in scientific format. internal - Internal-justify. left - Left-justify. right - Right-justify. dec - Insert or extract integer values in decimal format. hex - Insert or extract integer values in hexadecimal (base 16) format. oct - Insert or extract values in octal (base 8) format. noshowbase - Do not prefix value with its base. showbase - Prefix value with its base. noshowpoint - Do not show decimal point if not necessary. showpoint - Always show decimal point when inserting floating-point values. noshowpos - Don't insert plus sign (+) if number >= 0. showpos - Do insert plus sign (+) if number >=0. noskipws - Do not skip initial white space on extracting. skipws - Skip initial white space on extracting. nouppercase - Don't replace lowercase letters by uppercase equivalents.

Page 1

Name : Bhavin M Shah Roll No : 45


uppercase - Replace lowercase letters by uppercase equivalents. unitbuf - Flush buffer after an insert. nounitbuf - Don't flush buffer after each insert. Some of the more commonly used manipulators are:

1. endl:

Inserts a new-line character. Additionally, for buffered streams, endl flushes the buffer (i.e. writes all unwritten characters in the buffer to the output sequence).

Example: cout << "Exforsys" << endl; cout << "Training"; Output: Exforsys Training

2. setw:
This Setw () stands for the set width. The Setw () manipulator is used to set the width of the word to be displayed on screen. The header file that must be included while using setw manipulator is <iomanip.h> Example: #include <iostream.h> #include <iomanip.h> int main () { cout << setw (10); cout << 77 << endl; return 0; } Output: 77

3. setfill:

Page 2

Name : Bhavin M Shah Roll No : 45


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

Example: #include <iostream.h> #include <iomanip.h> int main () { cout << setfill ('x') << setw (10); cout << 77 << endl; return 0; } Output: xxxxxxxx77

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

These two forms are used when the keywords fixed or scientific are appropriately used before the setprecision manipulator. The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation. The keyword scientific, before the setprecision manipulator, prints the floating point number in scientific notation. Example: // setprecision example #include <iostream> #include <iomanip> int main () { double f =3.14159; cout << setprecision (5) cout << setprecision (9) cout << fixed; cout << setprecision (5) cout << setprecision (9) return 0; }

<< f << endl; << f << endl; << f << endl; << f << endl;

Page 3

Name : Bhavin M Shah Roll No : 45


Output: 3.1416 3.14159 3.14159 3.141590000 Q.2) Write a program which reads some text from the keyboard including spaces, special character, line feed and display the following information about the text you enter. 1. number of line 2. number of spaces 3. number of characters 4. number of words Ans.

Program:
#include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { char str[50]; int i,c=0,w=0,s=0,l=0,sp=0; clrscr(); cout<<"Enter the string\n"; gets(str); cout<<str; if(strlen(str)!=0) w++; for(i=0;str[i]!='\0';i++) { if(str[i]==32) { s++;

Page 4

Name : Bhavin M Shah Roll No : 45


if(str[i+1]!=32) w++; } else if(str[i]=='.') l++; else if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122)) c++; else if(str[i]=='\"' || str[i]=='\'' || str[i]=='!' || str[i]==',' || str[i]==';') sp++; } cout<<"\nNo. of spaces="<<s<<"\n"; cout<<"No. of words="<<w<<"\n"; cout<<"No. of lines="<<l<<"\n"; cout<<"No. of characters="<<c<<"\n"; cout<<"No of special characters="<<sp<<"\n"; getch(); }

OUTPUT:

Page 5

Name : Bhavin M Shah Roll No : 45

Q3.)Explain the use of following operators. 1. * 2. & 3. :: 4. . 5. ++ Ans. 1. * operator:

As Pointer operator

It is pointer to a variable.

Example : A=*Var; Var will point to a variable A.

As Aritmetic operator

It is used for multiplying two variables.

Example:

Page 6

Name : Bhavin M Shah Roll No : 45


Assume variable A holds 10 and variable B holds 20, then A * B will give 200 2. & operator: & as Pointer operator

It returns the address of an variable.

Example : &a; will give actual address of the variable a. & as Bitwise AND Operator

It copies a bit to the result if it exists in both operands.

The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Example: Assume variable A holds 60 and variable B holds 13 then (A & B) will give 12 which is 0000 1100

3.

:: Scope Resolution Operator : The :: operator is known as Scope Resolution operator in C++.

To access the Global variables when same variable name exist in Local scope.In this case the the local variable can be accessed normally but when we want to access global variable we have to use :: (Scope Resolution) operator.

Its use is to define the member functions outside the class. In this case when we want to define the member function whose prototype is declared inside the class.

Page 7

Name : Bhavin M Shah Roll No : 45


Scope resolution operator is used with static data members and static member functions

You can tell the compiler to use the global identifier rather than the local identifier by prefixing the identifier with ::, the scope resolution operator. :: identifier class-name :: identifier namespace :: identifier The identifier can be a variable or a function.

If you have nested local scopes, the scope resolution operator does not provide access to identifiers in the next outermost scope. It provides access to only the global identifiers.

4.

. (Dot ) Member Operator :

The . (dot) operator is used to access class, structure, or union members. The member is specified by a postfix expression, followed by a . (dot) operator, followed by a possibly qualified identifier or a pseudo-destructor name. The postfix expression must be an object of type class, struct or union. The name must be a member of that object. The value of the expression is the value of the selected member. If the postfix expression and the name are lvalues, the expression value is also an lvalue. If the postfix expression is type-qualified, the same type qualifiers will apply to the designated member in the resulting expression.

EXAMPLE: namespace ns { struct type { int var; }; }

In this case, to refer to the structure, which is a member of a namespace, use ::. To access the variable in an object of a particular type, you use .. ns::type obj; obj.var = 1;

5.

++ Increment operator:

Page 8

Name : Bhavin M Shah Roll No : 45


The ++ (increment) operator adds 1 to the value of a scalar operand, or if the operand is a pointer, increments the operand by the size of the object to which it points. The operand receives the result of the increment operation. The operand must be a modifiable lvalue of arithmetic or pointer type. You can put the ++ before or after the operand. If it appears before the operand, the operand is incremented. The incremented value is then used in the expression. If you put the ++ after the operand, the value of the operand is used in the expression before the operand is incremented. Example : play = ++play1 + play2++; is similar to the following expressions; play2 is altered before play: int temp, temp1, temp2; temp1 = play1 + 1; temp2 = play2; play1 = temp1; temp = temp1 + temp2; play2 = play2 + 1; play = temp; The result has the same type as the operand after integral promotion. The usual arithmetic conversions on the operand are performed. Q4.)Explain the data types and control structures in c++? Ans. The concept of a data type One of the reasons C++ requires all variables to be declared is that doing so constrains their contents to values of a particular data type. From a formal perspective, a data type is defined by two properties: a domain, which is the set of values that belong to that type, and a set of operations, which defines the behavior of that type. For example, the domain of the type int includes all integers (. . . 2, 1, 0, 1, 2 . . .) up to the limits established by the hardware of the machine. In C++ data types are of two types:-

1. Fundamental Data Types: As the name suggests these are the atomic or the
fundamental data types in C++.

2. Derived Data Types: These are the data types which are derived from the
fundamental data types. It is further divide into two categories

Page 9

Name : Bhavin M Shah Roll No : 45

i)Built-In

and

ii)User-defined

Integer types: Name bool char short Size (in bits, on x86) 8 (top 7 bits are ignored) 8 16 Range 0 or 1 -128 to 127(signed) or 0255(unsigned) -32768 to 32767(signed) or 065536(unsigned) -2147483648 to 2147483647(signed) or 0-4294967296(unsigned) same as int Notes C++ only standard issue "byte" just like a char, only twice as large standard-issue integer number type ditto

int

32 32 (can be 64 on other architectures)

long

Floating Point types: Name Float Double Size (in bits, on x86) 32 64 Range +/- 1.4023x10-45 to 3.4028x10+38 +/- 4.9406x10-324 to 1.7977x10308 Notes general purpose realnumber higher-precision real number

Built-In Derived Data Type

1. Arrays: Arrays refer to a list of finite number of same data types. The data in the

array can be accessed by an index number ranging from 0 to n(where n is the number of data element it can store). Ex- if arr[3] is an array of int(egers) then the different values in the array can be accessed as shown below. arr[0], arr[1],arr[2] when we declare an array such as the one sown above then by arr[3] we mean that we want three elements in the array and hence while accessing arr[2] is the last element. 2. Pointer: A pointer is a variable that holds the memory address of other variable. It is also of different data types, ex- char pointer can store address of only char variables, int pointer can store address of int variables and so on. 3. Reference: A reference in the simplest sense is an alias or alternate name for a previously defined variable.

Page 10

Name : Bhavin M Shah Roll No : 45


User-Defined Derived Data Types

1. Class: A class is a collection of variables and function under one reference name.

it is the way of separating and storing similar data together. Member functions are often the means of accessing, modifying and operating the data members (i.e. variables). It is one of the most important features of C++ since OOP is usually implemented through the use of classes. 2. Structure: In C++ structure and class same except for some very minor differences. 3. Union: A union is a memory location shared by two or more different variables, generally of different data types. Giving more details here would only confuse you; Ill leave it for future articles. 4. Enumerations: It can be used to assign names to integer constants. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. Conditional structure: if and else The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: For example: 1 if (x == 100) 2 cout << "x is 100"; 3 else 4 cout << "x is not 100"; prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. Iteration structures (loops) Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. The while loop

Page 11

Name : Bhavin M Shah Roll No : 45


Its format is: while (expression) statement Its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop: #include <iostream.h> int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n"; return 0; } Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! The do-while loop Its format is: do statement while (condition); Its functionality is exactly the same as the while loop, except that condition in the dowhile loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0. #include <iostream.h> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; } Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277

Page 12

Name : Bhavin M Shah Roll No : 45


You entered: 160277 Enter number (0 to end): 0 You entered: 0 The for loop Its format is: for (initialization; condition; increase) statement; Its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter


variable. This is executed only once. 2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2. Here is an example of countdown using a for loop: #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): // break loop example #include <iostream.h>

Page 13

Name : Bhavin M Shah Roll No : 45

int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; } 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: // continue loop example #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

The goto statement

goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. 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 (:).

Page 14

Name : Bhavin M Shah Roll No : 45


#include <iostream.h> int main () { int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The exit function exit is a function defined in the stdlib library. The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

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. The selective structure: switch. The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following: switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements }

Page 15

Name : Bhavin M Shah Roll No : 45

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure. If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure. Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).

Q.5) Explain the features of OOP? Ans. The programming in which data is logically represented in the form of a class and physically represented in the form an object is called as object oriented programming (OOP). OOP has the following important features. Class : In OOP languages it is must to create a class for representing data. Class contains variables for storing data and functions to specify various operations that can be performed on data. Class will not occupy any memory space and hence it is only logical representation of data. Data Encapsulation : Within a class variables are used for storing data and functions to specify various operations that can be performed on data. This process of wrapping up of data and functions that operate on data as a single unit is called as data encapsulation. Data Abstraction : Within a class if a member is declared as private, then that member cannot be accessed from outside the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction. Advantage of data abstraction is security. Polymorphism :

Page 16

Name : Bhavin M Shah Roll No : 45


Polymorphism means having more than one form. Polymorphism can be achieved with the help of overloading and overriding concepts. Polymorphism is classified into compile time polymorphism and runtime polymorphism. Object And Instance : Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area. When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object. Inheritance : Creating a new class from an existing class is called as inheritance. When anew class requires same members as an existing class, then instead of recreating those members the new class can be created from existing class, which is called as inheritance. Advantage of inheritance is reusability of the code. During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class.

Q.6) Explain call by reference and call by value? Ans. Call by value method: The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows. EXAMPLE: #include <iostream.h> void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put x into y */

Page 17

Name : Bhavin M Shah Roll No : 45

return; } int main () { // local variable declaration: int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; // calling a function to swap the values. swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; } return 0;

Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200 Which shows that there is no change in the values though they had been changed inside the function. Call by reference method: The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. EXAMPLE: #include <iostream.h> void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put x into y */ return;

Page 18

Name : Bhavin M Shah Roll No : 45


} int main () { // local variable declaration: int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; } return 0;

Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100

Q.7) Explain structure and union? Ans. Structure: A structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name. Declaring a Structure: The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces "{"and "}". Finally, the closed braces end with a semicolon denoted as ";" following the statement. The above structure declaration is also called a Structure Specifier.

Page 19

Name : Bhavin M Shah Roll No : 45


Example: Three variables: custnum of type int, salary of type int, commission of type float are structure members and the structure name is Customer. This structure is declared as follows:

In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer. Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure. To declare Structure Variable This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name. In the above example, structure variable cust1 is defined as:

What happens when this is defined? When a structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type int and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum, 2 bytes for salary and 4 bytes for commission.

Page 20

Name : Bhavin M Shah Roll No : 45


To access structure members To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly: structure_variable_name.member_name For example: A programmer wants to assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1 this is written as:

Union: Union is a user-defined type that uses same block of memory for every its list member. Union may be useful when it is necessary to work with different representation of same binary data. Declaring a Union Begin the declaration of a union with the union keyword, and enclose the member list in curly braces: // declaring_a_union.cpp union DATATYPE // Declare union type { char ch; int i; long l; float f; double d; } var1; // Optional declaration of union variable int main() { }

Example :

Page 21

Name : Bhavin M Shah Roll No : 45


// using_a_union.cpp #include <stdio.h> union NumericType { int iValue; long lValue; double dValue; }; int main() { union NumericType Values = { 10 }; printf_s("%d\n", Values.iValue); Values.dValue = 3.1416; printf_s("%f\n", Values.dValue); }

// iValue = 10

Q.8) W.A.P to delete the spaces from the text entered by the user? Ans.

PROGRAM:
#include<iostream.h> #include<conio.h> #include<stdio.h> void main() { int i,j; char str[30]; clrscr(); cout<<"Enter the string\n"; gets(str); for(i=0;str[i]!='\0';i++) { if(str[i]==32) { for(j=i;str[j]!='\0';j++)

Page 22

Name : Bhavin M Shah Roll No : 45


str[j]=str[j+1]; i=i-1; } } cout<<endl<<str; getch(); }

OUTPUT:

Q.9) Explain new and delete operators in dynamic memory management?

Page 23

Name : Bhavin M Shah Roll No : 45


Ans. C++ supports dynamic allocation and deallocation of objects using the new and delete operators. These operators allocate memory for objects from a pool called the free store. The new operator calls the special function operator new, and the delete operator calls the special function operator delete. NEW: In order to request dynamic memory we use the operator new. new is followed by a data type specifier and if a sequence of more than one element is required then the number of these are specified within the brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is: pointer = new type pointer = new type [number_of_elements] The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of a particular type specified, where number_of_elements is an integer value representing the amount of these. DELETE: Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is: 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. These are intended to replace malloc() and free() in the C standard library. To give an example of how these are similar and how they differ, suppose that we want to allocate a 100-long vector of integers for some purpose. In C, we would say: int* ip; ip = (int*)malloc(sizeof(int) * 100); ... free((void*)ip); With new/delete in C++, we would have: int* ip; ip = new int[100]; ... delete ip;

Page 24

Name : Bhavin M Shah Roll No : 45

The most obvious difference is that the C++ approach takes care of the low-level details necessary to determine how many bytes to allocate. With the C++ new operator, you simply describe the type of the desired storage, in this example "int[100]". Q.10) What is data encapsulation? Explain its importance? How data encapsulation ensures security? Explain it with the suitable example. Ans. Encapsulation is the process of binding together of Data and Code. It can also be defined as the concept that an object totally separates its interface from its implementation. The concept of Encapsulation hides the implementation details behind its interface

All C++ programs are composed of following two fundamental elements:

1. Program statements (code): This is the part of a program that performs actions
and they are called functions. program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example: class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.

2. Program data: The data is the information of the program which affected by the

Page 25

Name : Bhavin M Shah Roll No : 45


To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program. Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible. Data Encapsulation Example: Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example: #include <iostream> class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }

When the above code is compiled and executed, it produces following result: Total 60

Page 26

Name : Bhavin M Shah Roll No : 45


Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly. Q.11) W.A.P. to count the number of words using Enum? Ans.

PROGRAM:

#include<iostream.h> #include<conio.h> #include<stdio.h> enum flag{false,true}; void main() { int i,c=0; char ch; flag word=false; clrscr(); cout<<"Enter the string\n"; do { ch=getche(); if((ch==32)||(ch=='\r')) { if(word) { c++; word=false; }

Page 27

Name : Bhavin M Shah Roll No : 45


} else if(!word) { word=true; } }while(ch!='\r'); cout<<"\nNumber of words="<<c<<endl; getch(); }

OUTPUT:

Page 28

You might also like