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

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. << f << endl. If a value does not entirely fill a field. } << f << endl.Name : Bhavin M Shah Roll No : 45 This is used after setw manipulator. << f << endl. cout << 77 << endl. cout << setprecision (5) cout << setprecision (9) cout << fixed. << f << endl.14159. Example: // setprecision example #include <iostream> #include <iomanip> int main () { double f =3.h> int main () { cout << setfill ('x') << setw (10). The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation. Page 3 . } Output: xxxxxxxx77 4. cout << setprecision (5) cout << setprecision (9) return 0. before the setprecision manipulator. setprecision: The setprecision Manipulator is used with floating point numbers. The keyword scientific. return 0. then the character specified in the setfill argument of the manipulator is used for filling the fields. prints the floating point number in scientific notation. Example: #include <iostream.h> #include <iomanip. It is used to set the number of digits printed to the right of the decimal point.

c=0.i++) { if(str[i]==32) { s++. Page 4 . line feed and display the following information about the text you enter.2) Write a program which reads some text from the keyboard including spaces.str[i]!='\0'.s=0. int i.l=0.14159 3. number of words Ans. number of line 2.1416 3. gets(str).h> #include<stdio.Name : Bhavin M Shah Roll No : 45 Output: 3.14159 3. number of characters 4. cout<<"Enter the string\n".w=0. clrscr(). for(i=0.  Program: #include<iostream.h> #include<string.sp=0. cout<<str. special character.141590000 Q.h> #include<conio. if(strlen(str)!=0) w++. number of spaces 3.h> void main() { char str[50]. 1.

cout<<"No of special characters="<<sp<<"\n". }  OUTPUT: Page 5 . } cout<<"\nNo. of spaces="<<s<<"\n". of characters="<<c<<"\n". cout<<"No. of lines="<<l<<"\n".') sp++. else if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122)) c++. cout<<"No.Name : Bhavin M Shah Roll No : 45 if(str[i+1]!=32) w++. getch().') l++. } else if(str[i]=='. else if(str[i]=='\"' || str[i]=='\'' || str[i]=='!' || str[i]=='. cout<<"No.' || str[i]=='. of words="<<w<<"\n".

1.Name : Bhavin M Shah Roll No : 45 Q3. 1. * 2. & 3. Var will point to a variable A. Example: Page 6 . :: 4. • As Aritmetic operator • It is used for multiplying two variables. Example : A=*Var. * operator: • As Pointer operator • It is pointer to a variable.)Explain the use of following operators. ++ Ans. 5. .

Name : Bhavin M Shah Roll No : 45 Assume variable A holds 10 and variable B holds 20.  & as Bitwise AND Operator • It copies a bit to the result if it exists in both operands. the corresponding result bit is set to 0. Otherwise. • Its use is to define the member functions outside the class. then A * B will give 200 2. • The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. • To access the Global variables when same variable name exist in Local scope. • :: Scope Resolution Operator : The :: operator is known as Scope Resolution operator in C++. In this case when we want to define the member function whose prototype is declared inside the class. Example : &a. Page 7 . the corresponding result bit is set to 1. & operator:  & as Pointer operator • It returns the address of an variable.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. Example: Assume variable A holds 60 and variable B holds 13 then (A & B) will give 12 which is 0000 1100 3. will give actual address of the variable a. If both bits are 1.

If the postfix expression is type-qualified. the scope resolution operator does not provide access to identifiers in the next outermost scope. the expression value is also an lvalue. (dot) operator is used to access class. ns::type obj. (Dot ) Member Operator : • • The . (dot) operator. struct or union. EXAMPLE: namespace ns { struct type { int var. The member is specified by a postfix expression. obj.var = 1. The postfix expression must be an object of type class. the scope resolution operator. The value of the expression is the value of the selected member. The name must be a member of that object. you use . :: identifier class-name :: identifier namespace :: identifier The identifier can be a variable or a function. } In this case. followed by a .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 ::. or union members. }. followed by a possibly qualified identifier or a pseudo-destructor name. If the postfix expression and the name are lvalues. the same type qualifiers will apply to the designated member in the resulting expression. 5. • If you have nested local scopes. to refer to the structure. use ::. structure. 4. ++ Increment operator: Page 8 . To access the variable in an object of a particular type. It provides access to only the global identifiers. which is a member of a namespace. ..

If it appears before the operand.) up to the limits established by the hardware of the machine. 2. play1 = temp1. temp1 = play1 + 1. 1. Example : play = ++play1 + play2++. –1. . is similar to the following expressions. the operand is incremented. Q4.Name : Bhavin M Shah Roll No : 45 • The ++ (increment) operator adds 1 to the value of a scalar operand. The operand must be a modifiable lvalue of arithmetic or pointer type. a data type is defined by two properties: a domain. 0. temp = temp1 + temp2. the value of the operand is used in the expression before the operand is incremented. You can put the ++ before or after the operand. Fundamental Data Types: As the name suggests these are the atomic or the fundamental data types in C++. play = temp. increments the operand by the size of the object to which it points. . It is further divide into two categories Page 9 . play2 is altered before play: int temp. or if the operand is a pointer. The result has the same type as the operand after integral promotion. play2 = play2 + 1. . temp2. which is the set of values that belong to that type. For example. which defines the behavior of that type. and a set of operations. –2. 2 . The incremented value is then used in the expression. Derived Data Types: These are the data types which are derived from the fundamental data types. . The usual arithmetic conversions on the operand are performed. the domain of the type int includes all integers (. temp2 = play2. temp1. The operand receives the result of the increment operation. If you put the ++ after the operand. From a formal perspective. 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.)Explain the data types and control structures in c++? Ans. In C++ data types are of two types:- • 1.

It is also of different data types. arr[1].4028x10+38 +/. 3. on x86) 32 64 Range +/. 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.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. Reference: A reference in the simplest sense is an alias or alternate name for a previously defined variable.Name : Bhavin M Shah Roll No : 45 i)Built-In and ii)User-defined Integer types: Name bool char short Size (in bits.4023x10-45 to 3. Page 10 .char pointer can store address of only char variables.9406x10-324 to 1. Ex.7977x10308 Notes general purpose realnumber higher-precision real number Built-In Derived Data Type 1. Pointer: A pointer is a variable that holds the memory address of other variable. 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).4. arr[0]. int pointer can store address of int variables and so on.if arr[3] is an array of int(egers) then the different values in the array can be accessed as shown below. 2. 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. ex.

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

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

It works in the following way: 1. increase) statement. 9. or to force it to end before its natural end. 6. 2. n--) { cout << n << ". 1. If it is true the loop continues. finally. } cout << "FIRE!\n". Here is an example of countdown using a for loop: #include <iostream. condition is checked. For example. n>0. 4. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. 8. 2. otherwise the loop ends and statement is skipped (not executed).h> Page 13 . initialization is executed. 4. 5. } 10. 7. FIRE! Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. 3. statement is executed. Its main function is to repeat statement while condition remains true. it can be either a single statement or a block enclosed in braces { }. ".h> int main () { for (int n=10.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. the for loop provides specific locations to contain an initialization statement and an increase statement. we are going to stop the count down before its natural end (maybe because of an engine check failure?): // break loop example #include <iostream. condition. like the while loop. Generally it is an initial value setting for a counter variable. 3. It can be used to end an infinite loop. whatever is specified in the increase field is executed and the loop gets back to step 2. return 0. This is executed only once. As usual. But in addition.

6. n--) { cout << n << ". n>0. 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. 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. 6. 3. 7. 8. 3. 2. Page 14 . 4. 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. break. } 10. 5. return 0. } } return 0. 9. ". A label is made of a valid identifier followed by a colon (:). 7. which is then used as an argument for the goto statement. } 10. n>0. FIRE! The goto statement goto allows to make an absolute jump to another point in the program. 8. 4. cout << n << ". 1. for (n=10. 9.Name : Bhavin M Shah Roll No : 45 int main () { int n. n--) { if (n==5) continue. causing it to jump to the start of the following iteration. ". if (n==3) { cout << "countdown aborted!". } cout << "FIRE!\n".

8. 7. if (n>0) goto loop. return 0. The exitcode is used by some operating systems and may be used by calling programs.h> int main () { int n=10. case constant2: group of statements 2. Its prototype is: void exit (int exitcode). } 10. Its objective is to check several possible constant values for an expression. 4. 5.Name : Bhavin M Shah Roll No : 45 #include <iostream. 6. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. By convention. The purpose of exit is to terminate the current program with a specific exit code. break. 3. 1. loop: cout << n << ". 2. Its form is the following: switch (expression) { case constant1: group of statements 1. The selective structure: switch. an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened. n--. cout << "FIRE!\n". FIRE! The exit function exit is a function defined in the stdlib library. 9. The syntax of the switch statement is a bit peculiar. default: default group of statements } Page 15 . break. ". . . .

I. OOP has the following important features. 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).5) Explain the features of OOP? Ans. if it exists (since it is optional). it will execute group of statements 2 until a break keyword is found. Class contains variables for storing data and functions to specify various operations that can be performed on data. then that member cannot be accessed from outside the class. and then will jump to the end of the switch selective structure. Class : In OOP languages it is must to create a class for representing 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. that member is hidden from rest of the program. Data Encapsulation : Within a class variables are used for storing data and functions to specify various operations that can be performed on data. Finally. it executes group of statements 1 until it finds the break statement. the program will execute the statements included after the default: label. if it is. When it finds this break statement the program jumps to the end of the switch selective structure.e. Q. If it is equal to this. Class will not occupy any memory space and hence it is only logical representation of data. 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). Polymorphism : Page 16 .Name : Bhavin M Shah Roll No : 45 It works in the following way: switch evaluates expression and checks if it is equivalent to constant1. Advantage of data abstraction is security. This process of hiding the details of a class from rest of the program is called as data abstraction. If expression was not equal to constant1 it will be checked against constant2.

Advantage of inheritance is reusability of the code. 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. EXAMPLE: #include <iostream. When an object contains null. temp = x.Name : Bhavin M Shah Roll No : 45 Polymorphism means having more than one form. which is called as inheritance.6) Explain call by reference and call by value? Ans. C++ uses call by value to pass arguments. which is called as an object. Object And Instance : Class will not occupy any memory space. the class that is inherited is called as base class and the class that does the inheritance is called as derived class. Polymorphism can be achieved with the help of overloading and overriding concepts. then it is not possible to access the members of the class using that object. When an object is created without the keyword new. Inheritance : Creating a new class from an existing class is called as inheritance. then memory will not be allocated in heap I. Hence to work with the data represented by the class you must create a variable for the class. Q. In general. then instead of recreating those members the new class can be created from existing class.h> void swap(int x. instance will not be created and object in the stack contains the value null. When anew class requires same members as an existing class. When an object is created by using the keyword new.e. then memory will be allocated for the class in heap memory area. int y) { int temp. Polymorphism is classified into compile time polymorphism and runtime polymorphism. which is called as an instance and its starting address will be stored in the object in stack memory area. By default. /* put x into y */ Page 17 . /* put y into x */ y = temp. Consider the function swap() definition as follows. changes made to the parameter inside the function have no effect on the argument. In this case. /* save the value of x */ x = y. During inheritance. this means that code within a function cannot alter the arguments used to call the function.

value of b :200 After swap. value of a :100 Before swap. the address is used to access the actual argument used in the call. argument pointers are passed to the functions just like any other value. cout << "Before swap. } int main () { // local variable declaration: int a = 100. cout << "After swap. /* put y into x */ *y = temp.Name : Bhavin M Shah Roll No : 45 return. To pass the value by reference. value of a :100 After swap. value of a :" << a << endl. 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. /* save the value at address x */ *x = *y. b).h> void swap(int *x. value of a :" << a << endl. /* put x into y */ return. Output: Before swap. value of b :" << b << endl. cout << "After swap. Inside the function. int b = 200. swap(a. temp = *x. EXAMPLE: #include <iostream. which exchanges the values of the two integer variables pointed to by its arguments. } return 0. cout << "Before swap. This means that changes made to the parameter affect the passed argument. int *y) { int temp. value of b :200 Which shows that there is no change in the values though they had been changed inside the function. So accordingly you need to declare the function parameters as pointer types as in the following function swap(). // calling a function to swap the values. value of b :" << b << endl. Page 18 .

Page 19 . Declaring a Structure: The structure is declared by using the keyword struct followed by structure name. &b).7) Explain structure and union? Ans." following the statement. /* calling a function to swap the values. value of a :" << a << endl. cout << "After swap. * &a indicates pointer to a ie. value of b :100 Q. Then the structure members (variables) are defined with their type and variable names inside the open and close braces "{"and "}". value of a :100 Before swap. cout << "Before swap. char etc. Finally. float. */ swap(&a. value of b :200 After swap. address of variable a and * &b indicates pointer to b ie.Name : Bhavin M Shah Roll No : 45 } int main () { // local variable declaration: int a = 100. value of a :200 After swap. int b = 200. address of variable b. Output: Before swap. 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. the closed braces end with a semicolon denoted as ". Variables can be of any type: int. value of a :" << a << endl. The above structure declaration is also called a Structure Specifier. Structure: A structure is a collection of variables under a single name. value of b :" << b << endl. cout << "After swap. value of b :" << b << endl. cout << "Before swap. also called a tag. } return 0.

it allocates or reserves space in memory. Page 20 . structure variable cust1 is defined as: What happens when this is defined? When a structure is defined. declaring structures does not mean that memory is allocated. 2 bytes for salary and 4 bytes for commission. commission of type float are structure members and the structure name is Customer. Arrays behave in the same way. Structure declaration gives a skeleton or template for the structure. In the above example. To declare Structure Variable This is similar to variable declaration. it is seen that variables of different types such as int and float are grouped in a single structure name Customer. there are 3 structure members: custnum. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum. the data type is the name of the structure followed by the structure variable name.Name : Bhavin M Shah Roll No : 45 Example: Three variables: custnum of type int. two are of type int and one is of type float. salary of type int. salary and commission. This structure is declared as follows: In the above example. data type is defined followed by variable name. Of these. For structure variable declaration. The memory space allocated will be cumulative of all defined structure members. In the above example. For variable declaration.

Name : Bhavin M Shah Roll No : 45 To access structure members To access structure members. and enclose the member list in curly braces: // declaring_a_union. long l.cpp union DATATYPE // Declare union type { char ch. Declaring a Union Begin the declaration of a union with the union keyword. Union may be useful when it is necessary to work with different representation of same binary data. // Optional declaration of union variable int main() { } Example : Page 21 . double d. the operator used is the dot operator denoted by (. The dot operator for accessing structure members is used thusly: structure_variable_name. } var1.). int i.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. float f.

Values. long lValue. char str[30]. }.h> void main() { int i. cout<<"Enter the string\n". clrscr().8) W.j.h> #include<stdio.str[i]!='\0'. printf_s("%d\n". gets(str).h> union NumericType { int iValue.j++) Page 22 . } // iValue = 10 Q.i++) { if(str[i]==32) { for(j=i. printf_s("%f\n".str[j]!='\0'.cpp #include <stdio.  PROGRAM: #include<iostream.h> #include<conio. Values. for(i=0. int main() { union NumericType Values = { 10 }. Values.P to delete the spaces from the text entered by the user? Ans.dValue = 3. double dValue.dValue).Name : Bhavin M Shah Roll No : 45 // using_a_union.A.iValue).1416.

9) Explain new and delete operators in dynamic memory management? Page 23 . i=i-1. } } cout<<endl<<str. getch(). }  OUTPUT: Q.Name : Bhavin M Shah Roll No : 45 str[j]=str[j+1].

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

and that keeps both safe from outside interference and misuse. Program data: The data is the information of the program which affected by the Page 25 . called classes. // Height of a box }. By default. // Breadth of a box double height. Q. With the C++ new operator.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. in this example "int[100]". We already have studied that a class can contain private. 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. It can also be defined as the concept that an object totally separates its interface from its implementation. The variables length. breadth. Data encapsulation led to the important OOP concept of data hiding. Ans. all items defined in a class are private. C++ supports the properties of encapsulation and data hiding through the creation of user-defined types. Encapsulation is the process of binding together of Data and Code. This means that they can be accessed only by other members of the Box class. 2. protected and public members. This is one way encapsulation is achieved. Data encapsulation is a mechanism of bundling the data. Program statements (code): This is the part of a program that performs actions and they are called functions. } private: double length. For example: class Box { public: double getVolume(void) { return length * breadth * height. and height are private. // Length of a box double breadth. and not by any other part of your program. program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data. you simply describe the type of the desired storage.10) What is data encapsulation? Explain its importance? How data encapsulation ensures security? Explain it with the suitable example. The concept of Encapsulation hides the implementation details behind its interface All C++ programs are composed of following two fundamental elements: 1.

}. it produces following result: Total 60 Page 26 . return 0. } // interface to outside world int getTotal() { return total.addNum(30). accessible to other parts of your program). a. int main( ) { Adder a. All variables or functions defined after the public specifier are accessible by all other functions in your program. cout << "Total " << a. you must declare them after the public keyword.addNum(10). }.e. } // interface to outside world void addNum(int number) { total += number. a. private: // hidden data from outside world int total. } When the above code is compiled and executed. Consider the following example: #include <iostream> class Adder { public: // constructor Adder(int i = 0) { total = i..getTotal() <<endl.addNum(20). Making one class a friend of another exposes the implementation details and reduces encapsulation.Name : Bhavin M Shah Roll No : 45 To make parts of a class public (i. 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. The ideal is to keep as many of the details of each class hidden from all other classes as possible. a.

h> enum flag{false. Q. but is needed for the class to operate properly.Name : Bhavin M Shah Roll No : 45 Above class adds numbers together. and returns the sum.  PROGRAM: #include<iostream.A. clrscr(). do { ch=getche().11) W. cout<<"Enter the string\n". word=false. The private member total is something that is hidden from the outside world. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class.h> #include<stdio. if((ch==32)||(ch=='\r')) { if(word) { c++.h> #include<conio.c=0.true}.P. char ch. flag word=false. to count the number of words using Enum? Ans. } Page 27 . void main() { int i.

}  OUTPUT: Page 28 .Name : Bhavin M Shah Roll No : 45 } else if(!word) { word=true. getch(). cout<<"\nNumber of words="<<c<<endl. } }while(ch!='\r').

Sign up to vote on this title
UsefulNot useful