• No results found

Programming in C++ Solution Manuals MODULE 1:

N/A
N/A
Protected

Academic year: 2021

Share "Programming in C++ Solution Manuals MODULE 1:"

Copied!
120
0
0

Loading.... (view fulltext now)

Full text

(1)

MODULE – 1:

1. What do you mean by variables and keywords in C++? Can we declare a keyword as variable?

Ans: Variable is a storage place inside a computer where we can store some constant

values. Variable name must be alphabetic, alphanumeric, string but it can’t be constant value. Keywords are the special type of words that contains some special identification by the compiler. The keyword can’t be a variable.

2. What do you mean by scope of the variable means? What is Local Scope and What is global scope?

Ans: Declaration of a variable within the program is called as scope of the variable. There are 2 types of variables.

Local Scope: If the variable is declared within the void main( ) function then that is called as local scope.

Global Scope: If the variable is declared outside the variable then it is called as Global scope and the variable is said to be global variable.

Example:

3. What do you mean by a datatype? What is the use of an enum datatype? Ans: Data types are used to define a variable.

Name Description Size Range

char Character or small integer. 1byte signed: -128 to 127

unsigned: 0 to 255 short int

(short) Short Integer. 2bytes

signed: -32768 to 32767 unsigned: 0 to 65535

(2)

int Integer. 4bytes

signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295 long int

(long) Long integer. 4bytes

signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

bool Boolean value. It can take one of two

values: true or false. 1byte true or false

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)

long double Long double precision floating point

number. 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t Wide character. 2 or 4

bytes 1 wide character

enum datatype:

“enum” is an user defined datatype in which we can attach a name to a numbers, thereby it increases comprehensibility of the code. The “enum” keyword automatically assigns

0,1,2,3,4,=so on to the elements inside the enum data type. Example:

#include <iostream.h>

enum Language { English, French, German, Italian, Spanish }; int main() {

Language tongue = German;

cout << "\n Current language is " << tongue; return 0;

}

Output:

Current language is 2

4. What is the use of typedef datatype?

Ans: Sometimes it might be required to own types based on other existing data type. On that case “typedef” is used. Its syntax is: typedef existing_type new_type_name;

Example: typedef char C; typedef char g[89];

typedef char *p;

(3)

Ans: It is a special type of string that contains the input and output instructions. Streams are two types:

istream: It is an input stream. The user can input the data in istream. The istream contains the objects “cin>>”.

ostream: It is an output stream. The user can display the data in ostream. The ostream contains the object “cout<<”.

6. What do you mean by a manipulator?

Ans: Manipulator are the operators that are used to format the data display. The most commonly used manipulators are endl and setw. “endl” manipulator are used to end the existing line. “setw” is used to set the width of a necessary field.

Example: cout<<”Hello”<<endl; Example: setw(5); cout<<345<<12;

7. What are the different derived datatypes? Ans: The different derived datatypes are:

Array: An array is the collection of variables having similar datatype.

Function: Function is the block of statements that can be executed at a time. • Pointer: Pointer is used for allocating any memory location of the variables. • Structure/Union/Class: Structure/Union/Class is the collection of dissimilar

datatype.

8. What is the difference between the address stored in a pointer & value stored at that address?

Ans: We can assign the address stored in a pointer by the ampersand (&) which is called as reference operator. But we can assign the value stored at that address by asterisks (*) which is called as indirection operator.

Example:

Let us consider a variable “p” whose address is 2000 and the value stored at the address of “p” is 25.

So *p will be 25 and &p will be 2000. 9. What is the difference in structure and union?

Ans: The total memory occupied by the structure is equal to the total size of the variable. As for example:

struct student {

int rollno; //size of int is 2byte

char name[30]; //size of char is 1byte and name[30] is 30byte float mark; //size of float is 4byte

}; Here the size of the structure is 2 + 30 + 4 = 36 byte

But the total memory occupied by the union is maximum size of the variable declared inside the union.

(4)

union student {

int rollno; //size of int is 2byte

char name[30]; //size of char is 1byte and name[30] is 30byte float mark; //size of float is 4byte

}; Here the size of the structure is max(2,30,4) = 30 byte 10. What is the use of scope resolution operator in C++? Ans: Scope resolution operator is used for two purposes:

• It is used to define the global variable. Example:

#include<iostream.h> int i=20;

void main( ) {

cout<<"The global value of I is "<<::i }

• It is used to define a method outside the class or structure or union. Example: #include<iostream.h> class student { void mark( ); } student : : mark(int x) { cout<<"Enter mark"<<endl; cin>>x;

cout<<"Your mark is"<<x; } void main( ) { student s; s.mark( ); }

11. What is array of structure? What is pointer to array?

Ans: If we declare an structure with an array then it is called as array of structure. If we declare an array and the array elements can be accessed by the pointer then it is called as pointer to array.

(5)

Ans: Class is the user defined datatype that contains data members, member functions or methods (the functions that are declared inside the class).Object is an instance of the class. By using the objects we can access the methods or data members.

Example for the Class and Object: #include<iostream.h>

class computer //declaration of the class {

public: //Access Specifier int i, j;

software( ) //declaration of method {

cout<<"Enter Software id"; cin>>i;

} }

void main( ) {

computer abc; //initialisation of object

abc.software( ); //accessing the methods through the object }

Here we have declare the class as “computer” and the object as “abc”. 13. What do you mean by control structures in C++?

Ans: Control structures are most important in structured language C++. Generally control structures have body.

Some examples of control structure are:

• Jumping(goto statement)

• Looping(while, do=while, for)

• Conditional Statements(if, if=else, if=elseif=if, switch case)

14. What is looping?

Ans: Looping is the continuous execution of block of statement or single statement for a certain conditions. Looping statements in C++ are: while( ), do=while( ) and for( ) loop. 15. What is branching?

Ans: Branching is the execution of statement or block of statement for a certain condition. Branching statements are if, if=else, if=else if=else, switch( )=case. Branching is also called as decision making in C++. It is also called as conditional statements in C++. 16. What do you mean by an array? How integer array is different from character array?

Ans: An array is the collection similar datatype that have the common name. An array can be represented as:

(6)

Datatype <variable name> [size]; Example: int A[6];

An integer array is different from character array. Because in integer array we have to define the array as “int”. So the data inside integer array is always acts as integer type. But in character array we have to define the array by the data type as “char” type. So the array items in an character array can be character type.

17. What is the size of an array S[n][m][l]? Give an example.

Ans: The size of the array S[n][m][l] is n*m*l*(size of the data type).

Example the size of int S[5][6][10] is 5*6*10*(size of int that is 2) = 600byte 18. What do you mean by function? What are the types of function?

Ans: Function is the block of statement which can be executed at a time. The different type of functions is:

1. User define function: The function that can be declared by the user.

2. In built or library functions: These functions are already defined inside the C++ compiler.

19. How to declare an user defined function?

Ans: The general syntax of the user define functions are: #include<iostream.h>

void main( ) {

...

fun( ); //Calling of the function ...

}

void fun( ) //Defining the function {

... //Declaring the function ...

}

20. What do you mean by function prototyping? How function prototyping is different in C and C++?

Ans: In C++ a template is used when we define or declared a function. When function is called, the compiler uses the template to ensure that proper argument is passed, and the return value is treated correctly. Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself. These checks and controls did not exist in the C function prototyping.

In this way, function prototyping is different in C and C++.

(7)

Ans:

Nested loop: is the loop in which contains another loop. That means there are two loops, one is outer loop and another is inner loop.

Example:

For(int i=0; i<=9; i++) {

for(int j=8; j<=0; j--) {cout<<”Hello”; }

}

Nesting of function: During declaration of function if we declare a function inside the definition then it is called as nesting of function.

Example: Function1( ) { Declaration; Function2( ); } Function2( ) { Declaration; }

22. What is the basic difference in call by value and call by reference?

Ans: In call by value the value of the variable is passed inside the function, where as in call by value the address is passed inside the function.

23. What is inline function? Why inline function is used in C++?

Ans: By declaring a function as inline means the compiler replaces the function call with the corresponding function code. To eliminate the cost of calls to small functions C++ uses the inline function. For defining a function inline we must write the keyword “inline” before the function. The general declaration of the inline function is:

inline function-header {

function body }

Example:

inline double cube(double a) {

return(a*a*a); }

24. What are the situations where inline expansions may not work? Ans: Some of the situations where inline expansions may not work are: 1. For function returning values, if a loop, a switch, or a goto exists.

(8)

2. For functions not returning values, if a return statement exists. 3. If inline functions are recursive.

25. What is difference between inline function and macro. Ans:

Inline function Macro

1. It is a member function. 2. class <class_name> {

public: inline return. type

function_name(arg 1, arg 2, ... arg n)

{ }

3. It expands when it call.

4. It takes more time for execution. 5. It takes less memory space. 6. It checks error. 7. Example: #include<iostream.h> class circle { int r; float a;

public: inline void get( ); inline void cal( );

};

inline void circle : : get( ) {

cout<<"Enter Radius"; cin>>r;

}

inline void circle : : cal( ) { a = 3.141* r * r; cout<<"Area = " <<a; } void main( ) { circle obj; obj.get( ); obj.cal( ); } 1. It is a preprocessor.

2. # define macro_name macro_val

3. It expands before compilation of program.

4. It takes less time for execution. 5. It takes more memory space. 6. It does not check error. 7. Example: #define Area(r)(3.141*r*r) #include<iostream.h> void main( ) { int r; float a; cout<<"Enter Radius"; cin>>r; a = Area(r); cout<<"Area"<<a; }

(9)

26. What do you mean by function overloading? Explain.

Ans: Overloading means to the use of the same thing for different purposes. That means we can use the same function name to create functions that perform a variety of different tasks. This is also called as function polymorphism.

#include<iostream.h> int volume(int);

double volume(double, int); long volume(long, int, int); int main( ) { cout<<volume(10)<<endl; cout<<volume(2.5,8)<<endl; cout<<volume(100L,75,15)<<endl; return 0; } int volume(int s) { return(s*s*s); }

double volume(double r, int h) {

return(3.141*r*r*h); }

long volume(long l, int b, int h) { return(l*b*h); } OUTPUT: 1000 157.26 112500

27. What is the use of friend function? Give an example.

Ans: As a non-member function cannot have an access to private data of a class, still we want to share a particular function with more than one class. In such situations we can use friend functions that will be friendly with both the classes, thereby allowing the functions to have an access to the private data member of these classes.

The function declaration should be preceded by the keyword friend. Example:

#include<iostream.h> #include<conio.h>

(10)

class sample { int a; int b; public: void setvalue( ) { a=35; b=67; }

friend float mean(sample s); }; float mean(sample s); { return float(s.a+s.b)/2.0; } void main( ) { sample x; x.setvalue( ); cout<<"Mean is"<<mean(x)<<endl; getch( ); }

Some important points about friend function:

• It can declare any section of a class(private, protected, public) has same effect. • It is a non-member function.

• It must have argument of class type. • It need not require object for its execution.

• It is used to access private section data of a class. 28. What is the difference between malloc( ) and new?

Ans:

• The new operator automatically computes the size of the data object we need not used

sizeof( ) operator.

• It automatically returns the correct pointer type. It need not used cast operator. • It is possible to initialized the object while creating the memory space.

• The new and delete can be overloaded.

29. How to read and print one character (including spaces) at a time from keyboard? ANS: #include<iostream.h>

#include<conio.h> void main( )

(11)

{ Char ch; cout<<”Enter a character”, ch=getch( ); cout<<”out of character”<<ch; }

30. What is the difference between macro and inline member function? Ans:

Macro • It is a preprocessor. • Syntax:

#define <macro name> <macro declaration>

• It expands before compilation

• It does not check the error.

Inline function

• It can be a member function.

• Syntax:

class<class_name> {

public:

inline <return type>

method(arg1, arg2,....arg n) {

} }

• It expands at the time of execution of program.

• It checks the error.

31. What do you mean by static member function and static member function? Ans:

Static member function: These function is the class member functions. It is used only static member data or methods. It has no “this” pointer. It can be accessed by class name but not object. It can be declared with the keyword “static”.

Syntax:

class<class_name> {

public:

static <return_type> method(arg1, arg2, ..., arg n) {

statements; }

(12)

};

Static data member: It is initialized to zero when the first object of its class is created. No other initialization is permitted.

Only one copy of the that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.

Static data member can be visible within the class, but its life time is total the program. Example: static int count;

32. What do you mean by recursive function? Explain with an example. Ans:

Recursive Function: If a function calls itself then it is called as recursive function. Example: C++ Program to calculate factorial of a number using recursion.

#include<iostream.h> #include<conio.h> int fact(int); void main() { int a,b=0,c; clrscr();

cout<<"Enter the N value:"; cin>>a;

while(a<0)

{cout<<"\n\Enter only positive number.\n"; cout<<"Enter N value:"; cin>>a; } b=fact(a); cout<<b; getch(); } int fact(int x) { if(x==0) { return(1); } else { return((x)*(fact(x-1))); } }

(13)

33. Write a program to check prime number using recursion. Ans: #include<iostream.h> int isPrime(int); int main(){ int num,prime;

cout<<"Enter a positive number: "; cin>>num;

prime = isPrime(num);

if(prime==1)

cout<<num<<” “<<"is a prime number"<<endl;

else

cout<<num<<” “<<” is not a prime number";

return 0;

}

int isPrime(int num){ static int i=2; if(i<=num/2){ if(num%i==0) return 0; else{ i++; isPrime(num); } } return 1; } Output:

Enter a positive number: 13 13 is a prime number

34. What are the different functions used in handling of strings? Ans:

1. strlen() function:

This function counts and returns the number of characters in a string. The length does not include a null character.

Syntax:

n=strlen(string);

Where n is integer variable. Which receives the value of length of the string. Example:

length = strlen(“Hollywood”);

(14)

2. strcat() function:

when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat( ) function joins 2 strings together. It takes the following form

strcat(string1,string2)

string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged.

Example:

strcpy(string1,”Soumya”); strcpy(string2,”Sourabha”); cout<<strcat(string1,string2);

From the above program segment the value of string1 becomes SoumyaSourabha. The string at str2 remains unchanged as Sourabha.

3. strcmp() function:

In C++ you cannot directly compare the value of 2 strings in a condition like if (string1==string2)

Most libraries however contain the strcmp( ) function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp( ) is given below:

strcmp(string1,string2)

String1 & string2 may be string variables or string constants. String1 & string2 may be string variables or string constants some computers return a negative if the string1 is

alphabetically less than the second and a positive number if the string is greater than the second.

Example:

strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.

strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’.

strcmp(“The”, “the”) will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.

4. strcmpi() function:

This function is same as strcmp() which compares 2 strings but not case sensitive. Example

strcmpi(“THE”,”the”); will return 0. 5. strcpy() function:

C++ does not allow you to assign the characters to a string directly as in the statement name=”Robert”;

Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below.

(15)

strcpy(string1,string2);

strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.

strcpy(Name,”Robert”);

In the above example Robert is assigned to the string called name. 6. strlwr () function:

This function converts all characters in a string from uppercase to lowercase. Syntax:

strlwr(string); For example:

strlwr(“SOUMYA”) converts to soumya. 7. strrev() function:

This function reverses the characters in a string. Syntax:

strrev(string);

For ex strrev(“program”) reverses the characters in a string into “margrop”. 8. strupr() function:

This function converts all characters in a string from lower case to uppercase. Syntax :

strupr(string);

For example strupr(“soumya”) will convert the string to SOUMYA. Example: C++ Program for Sub String.

#include<iostream.h> #include<conio.h> void main() { char a[30],b[30]; int i, j, l1, l2, c, f; clrscr( ); cout<<"OUTPUT\n"; cout<<"\n\n";

cout<<"\nEnter First String:"; cin>>a;

cout<<"\nEnter String to Search:"; cin>>b; l1=strlen(a); l2=strlen(b); j=0; c=0; f=0; for(i=0;i<l1;i++) { x:

(16)

if(b[j]==a[i]) { c++; f=1; j++; if(c==l2)goto y; } else { if(f==1) { j=0; c=0; f=0; goto x; } } } y: if(c==l2) cout<<"\n\t\tWord Found"; else

cout<<"\n\t\tWord Not Found"; getch();

}

35. Write a program in C++ using switch case statement to calculate the grade of BPUT. Ans:

#include<iostream.h> #include<conio.h> void main( ) {

int mark, index;

cout<<"Enter the Mark of a student(between 100):\t"; cin>>mark;

index= mark/10; switch(index) {

case 10:

case 9: cout<<"\n The grade is => O"; break; case 8: cout<<"\n The grade is => E"; break; case 7: cout<<"\n The grade is => A"; break; case 6: cout<<"\n The grade is => B"; break; case 5: cout<<"\n The grade is => C"; break; case 4:

case 3: cout<<"\n The grade is => D"; break; case 2:

(17)

case 0: cout<<"\n The grade is => F.\n You are failed."; break;

default: cout<<"\nInvalid Mark. Please Enter Mark between 0 to 100"; }

getch( ); }

Output:

Enter the Mark of a student(between 100): 83 The grade is => E

36. Write a C++ program for Check for Vowel using switch case statement. Ans: #include<iostream.h> #include<conio.h> void main( ) { char ch; clrscr();

cout<<"Enter any character"; cin>>ch; switch(ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u':

case 'U': cout<<"The Entered Character”<<ch<<” is a Vowel”; break; default: cout<<ch<<” is not a vowel"; break;

} getch(); }

37. Write a C++ Program For Binary to Decimal. Ans: #include<iostream.h> #include<conio.h> #include<math.h> void main() { int s=0,z=0,n,t;

(18)

clrscr();

cout<<"Enter the n value"; cin>>n; while(n>0) { t=n%10; s=s+(t*pow(2,z++)); cout<<"s="<<s<<endl; n=n/10; }

cout<<"given number is="<<s<<endl; getch();

}

38. Write a C++ program to find the sum of digits. Ans: #include<iostream.h> #include<conio.h> main() { int n,q,r,s=0; clrscr();

cout<<“\n Enter the no"; cin>>n; while(n!=0) { q=n/10; r=n-q*10; s=s+r; n=q; }

cout<<“\n the sum of digits :”<<s; getch();

}

39. Write a C++ program to find all the sum of sequences of even & odd number. Ans:

#include<iostream.h> #include<conio.h> void main( ) {

int i, range, sum=0; clrscr( );

(19)

cin>>range;

for(i=0; i<=range; i=i+2) {

sum = sum + i; }

cout<<"\n\n\tThe sum of Even Number Sequence is "<<sum; for(i=1; i<=range; i=i+2)

{

sum = sum + i; }

cout<<"\n\n\tThe sum of Odd Number Sequence is "<<sum; getch( );

}

40. Example: C++ program to find permutation. Ans: #include<iostream.h> #include<stdlib.h> int lev=-1,n,val[50],a[50]; void main() { int i,j; clrscr();

cout<<"Enter how many numbers"<<endl; cin>>n; for(i=0;i<n;i++) { val[i]=0; j=i+1; cin>>a[j]; } visit(0); getch(); } visit(int k) { int i; val[k]=++lev; if(lev==n) { for(i=0;i<n;i++) cout<<a[val[i]]; cout<<” “; }

(20)

for(i=0;i<n;i++) if(val[i]==0) visit(i); lev--; val[k]=0; }

41. Write a program to calculate the square of a number using the pointer arithmatic concept. Ans: #include<iostream.h> #include<conio.h> void main( ) { int x, y, *ptr;

cout<<"Enter the number to calculate the square"; cin>>x; ptr=&x; *ptr=(*ptr)*(*ptr); cout<<"The square is %d"<<x; getch( ); } output:

Enter the number to calculate the square 5 The square is 25

42. Write a program to calculate the length of string using pointer. Ans: #include<iostream.h> #include<conio.h> void main( ) { char str[20]; int len=0; char *ptr; clrscr( ); cout<<"Enter a string"; gets(str); ptr=str; for(len=0; *ptr!='\0'; ptr++) { len++; }

(21)

getch( ); }

output:

Enter a string SOUMYASOURABHA The length of the string is 14

43. Write a C++ program to reverse a string using pointer. Ans: #include<iostream.h> #include<conio.h> void main( ) { char str[30]=""; int i; clrscr( );

cout<<"Please Enter a string to reverse"; cin>>str;

for(i=0; str[j]!='\0'; i++)

cout<<"The reverse string is"; i--;

for(; i>=0; i--) cin>>str[i]; getch( ); }

44. What do you mean by typecasting? Explain Explicit and implicit conversion. What are the rules associated with type conversion?

Ans:

Type conversion is done in two ways: 1. Implicit conversions

2. Explicit conversions

1. Implicit type Conversion:

Whenever C++ finds mixed data type in an expression, it performs the conversion

automatically. C++ automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic conversion is known as implicit conversion.

Example: Implicit conversation: #include<iostream.h>

(22)

#include<conio.h> void main( ) {

int x; float y, sum, avg; clrscr( ); x=80; y=40.8;

sum=x+y;

cout<<"The sum is : "<<sum; avg=sum/2;

cout<<"\nThe average is : "<<avg; getch( ); } Output: The sum is : 120.80 The average is : 60.40 2. Explicit Conversion:

Besides implicit conversion, sometimes we want to force a type conversion in a way that is different from automatic conversion. As for example if you want to calculate the ratio of male to female in a town then the expression will be ratio = no-of-female/ no-of-male;

Because no-of-female and no-of-male are declared as integer, the decimal part of the result of the division would be lost and ratio would represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as:

ratio = (float) no-of-female/no-of-male;

The operator (float) converts the no-of-female to floating point for the purpose of evaluation of the expression and then using rule of automatic conversion. The division is performed in floating point made this retaining the fractional part of result.

The process of such a local conversion is known as explicit conversion or casting a value. The syntax is: (type_name) expression. Example: average = sum/(float) i ;

Example: Example of Explicit conversion: #include<iostream.h>

#include<conio.h> void main( ) {

int a =76; float f = 7.9; double d = 98.99; char c = 'L'; signed s = -1; clrscr( ); cout<<"\n int in char format: "<<a;

cout<<"\n float in int format: "<<(int)f;

cout<<"\n double in char format: “<<(char)d; cout<<"\n char in int format: "<<(int)c;

cout<<"\n signed in unsigned format: “(unsigned)s; getch( );

(23)

Output:

int in char format: L float in int format: 7 double in char format: b char in int format: 76

signed in unsigned format: 65536 Rules for Type Conversion:

• If one operand is unsigned int, the other will be converted into unsigned int and the result will be unsigned into long int and the result will be long int.

• If one of the operand is unsigned long int, the other will be converted into unsigned long int and the result will be unsigned long int.

• If one of the operand is float, the other will be converted into float and the result will be float.

• If one of the operand is double, the other will be converted to double and the result

will be double.

• If one of the operand is long double, the other will be converted to long double and the result will be long double.

45. What do you mean by RTTI? Ans:

The RTTI means the information of type of a data is known as run time. it is achieved by typeid( )operator.

syntax char*object class=typeid(objected)name( ) ex. #include<iostream.h> #include<typeinfo.h> classx { public: void dis ( ) { cout<<”ctc” } }; class y:public x { public: void dis( ) {

cout<<”Soumya Sourabha Patnaik”; }

(24)

}; void main() { x*ob; cout<<typeid(ob).name( ); y*obj; cout<<typeid(obj).name( ); }

46. What do you mean by file handling in C++? Ans:

C++ provides the following classes to perform output and input of characters to/from files: • ofstream: Stream class to write on files

ifstream: Stream class to read from files

fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:

Example 14.1: basic file operations. #include <iostream.h>

#include <fstream.h> int main () {

ofstream myfile;

myfile.open ("example.txt"); myfile << "Writing this to a file.\n";

myfile.close();

return 0;

} Output:

[file example.txt]

Writing this to a file.

This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.

47. What is the different state flags associated with file? Ans:

(25)

bad( ) :

Returns true if a reading or writing operation fails. For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.

fail( ) :

Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.

eof( ) :

Returns true if a file open for reading has reached the end. good( ) :

It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true.

48. What is the work of set_terminal( )? Ans:

It is used to transfer the control to specified error handing function.

It contains a single argument of function name where control is transferred. Exmp:#include<iostream.h> #include<except.h> class A{ }; class B{ }; void skip( ) {

cout<<”error can be handle”; } void main( ) { set-terminal(skip); try { throw(two); } catch(one) {

cout<<”exception one is caught”; }

}

Here the throw statement throw two but it can not match with any catch block .so skip( )is execute.

(26)

49. What is the difference between static array and dynamic array. Ans:

Static array:

In such case to allocate memory at the time of compilation of program we use static array.

Example: int a[10];

It allocates 20 byte at the time of compilation.

Suppose the user input 5 element then it uses 10bytes and does not use 10 bytes. Suppose the user input 11 elements then it can’t be accepted because it requires 22 bytes. So this is the disadvantage of static array.

Program:

#include<iostream.h> void main( )

{

int a[10], i, n;

cout<< "Enter how many data"; cin>>n;

cout<<"Enter data"; for(i=0; i<n; i++) cin>> a[i]; for(i=0; i<n; i++) cout<< a[i]; }

Dynamic array:

To allocate memory at the time of execution of program is known as dynamic array. It is held by new operator.

Program: #include<iostream.h> void main( ) { int i, n, *p; clrscr( ); cout<<"Enter range"; cin>>n; p = new int[n];

(27)

cout<<"Enter data"; for(i=0; i<n; i++) cin>>p[i]; for(i=0; i<n; i++) cout<<a[i]; }

50. Given a 2-dimensional m x n double array A. Declare the variable A, and write the c++ code required to allocate and deallocate the array (assume that m and n are declared and their values are known).

ANS: double A[m][n]; #define M 10 #define N 10 void main( ) { double A[M][N]; int r,c; cout<<enter data”; for(r=0;r<10;r++) { for(c=0;c<10;c++) cin>>A[r][c]; } for (r=0;r<10;r++) { for(c=0;c<3;c++) cout<<A[r][i]; cout<<”\n”; } }

Here the array Á’allocate 10 x10x8=800 bytes. #include<iostream.h> #define M 10 #define N 10 void main( ) {

double *A=new double[M][N]; int r,c;

cout<<enter data”; for(r=0;r<M;r++) {

(28)

for(c=0;c<N;c++) cin>>A[r][c]; } for(r=0;r<M;r++) { for(c=0;c<N;c++) cout<<A[r][c]; cout<,”\n”; } delete[ ]A; }

51. What does the reference operator do? What is the difference between passing an argument by reference and passing it by value?

Ans:

It create an alias name of a variable. Syntax:

datatype &var1 = var2; Example: #include<iostream.h> void main( ) { int a = s; int &b = a; cout<<a<<b; a++; cout << a << b; b++; cout << a << b; }

Here a and b variable have same address.

Call by Value Call by reference

1. In such case the value of the variable can pass as the function argument.

2. If any change in formal argument then no change in actual argument.

3. The formal argument allocates separate memory space.

4. The actual and formal argument have separate memory space.

5. Example:

1. In such case it creates an alias.

2. If any change in formal argument then

automatically change in actual argument.

3. The formal argument does not allocate

memory space.

4. The actual argument and formal

argument have same memory space.

(29)

#include<iostream.h> #include<conio.h> void main( ) {

void ex(int, int); int a, b;

cout<< "Enter 2 number"; cin>>a >>b;

ex(a,b); cout<<a<<b; }

void ex(int p, int q) { int temp; temp p; p = q; q= temp; cout << p<<q; } #include<iostream.h> #include<conio.h> void main( ) {

void ex(int &, int &); int a, b;

cout<< "Enter 2 number"; cin>>a >>b;

ex(a,b); cout<<a<<b; }

void ex(int x, int y) { int temp; temp x; x = y; y= temp; cout << x<<y; }

(30)

MODULE – 2

1. What do you mean by object oriented programming language? Why C++ is an object oriented language?

Ans: In object oriented language we have to create a class which is the collection of data members, member functions or methods etc. We have to access the elements inside the class through an object.

In C++ we can create a class and define the data members and member functions of that class. We again create an object of that class. Through that object we have to access those elements inside the class.

2. Why Java is a purely object oriented language where as C++ is not a purely object oriented language?

Ans: In Java we can’t create any program without using the class or object. But in C++ it may or may not require creating classes or objects. That means we can write the program in C++ both by creating the class and by not creating the class. Hence C++ is not a purely object oriented language.

3. What are the applications of OOPS? Ans: The various applications of OOPS are:

1. Real-time systems. 2. Simulation and modeling. 3. Object-oriented databases.

4. Hypertext, hypermedia and expertext. 5. AI and expert systems.

6. Neural networks and parallel programming. 7. Decision support and office automation systems. 8. CIM/CAM/CAD systems

4. What the basic difference is in between object oriented programming and object based programming? Give one example of each.

Ans:

Object-based programming is the style of programming that primarily supports

encapsulation and object identity. Languages that support programming with objects are said to be object-based programming languages. They do not support inheritance and

dynamic binding. Ada, Visual BASIC etc. are the examples of object-based programming

language.

Object-oriented programming incorporates all of object-based programming features

along with two additional features, namely, inheritance and dynamic binding. Java, C++,

Python, PHP etc are the examples of object oriented programming language. 5. What are the features of OOPS?

(31)

Inheritance:

Inheritance is the process of forming a new class from an existing class or base

class. The base class is also known as parent class or super class, The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming.

Multiple Inheritance:The mechanism by which a class is derived from more than one base class is known as multiple inheritance. Instances of classes with multiple inheritance have instance variables for each of the inherited base classes. C++ supports multiple inheritance.

Data Abstraction:

Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details.

Data Encapsulation:

Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible.

Polymorphism:

Polymorphism is in short the ability to call different functions by just using one type of function call. It is a lot useful since it can group classes and their functions together. Polymorphism means that the same thing can exist in two forms. This is an important characteristic of true object oriented design - which means that one could develop good OO design with data abstraction and inheritance, but the real power of object oriented design seems to surface when polymorphism is used. In C++,

polymorphism means that if the same message is sent to different objects, the object’s behavior depends on the nature of the object itself. This is sort of obvious for completely different objects, but the concept starts making sense when combined with inheritance.

Delegation:

Delegation is a way of making object composition as powerful as inheritance. In delegation two objects are involved in handling a request a receiving object delegates operations to its delegate. This is analogous to child class sending requests to the parent class.

(32)

Reusability:

This term refers to the ability for multiple programmers to use the same written and

debugged existing class of data. This is a time saving device and adds code efficiency to the language. Additionally, the programmer can incorporate new features to the existing class, further developing the application and allowing users to achieve increased performance. This time saving feature optimizes code, helps in gaining secured applications and facilitates easier maintenance on the application.

6. Why C++ is called as weakly typed language? What do you mean by strong typing? Ans:

The language which cannot support type casting is called as strong typed language. In C++ it can support typecasting. Type casting is possible in C++. That means we can convert any data type to any data type in C++. Hence C++ is a weakly typed language. 7. What are the advantages of OOPS?

Ans:

Through inheritance, we can eliminate redundant code and extend the use of

existing classes.

We can build programs from the standard working modules that communicate

with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity.

The principle of data hiding helps the programmer to build secure programs that

cannot be invaded by code in other parts of the program.

It is possible to have multiple instances of an object to co-exist without any interference.

It is possible to map objects in the problem domain to those objects in the

program.

It is easy to partition the work in a project based on objects.

The data-centered design approach enables us to capture more details of a

model in implementable form.

Object-oriented systems can be easily upgraded from small to large systems.

Message passing techniques for communication between objects makes the

interface descriptions with external systems much simpler.

Software complexity can be easily managed.

8. What is a class? How to define a class?

Ans: A class is a user defined data type which contains some data members, member functions or methods. We can declare a class by using the keyword “class”.

Syntax is:

class <class name> {

Declaration of the class; }

(33)

9. What is an object? Explain how to declare an object?

Ans: An object is an instance of the class. While accessing any element of a class we need to access through the object.

The object can be declared after the class or within the void main( ). Declaration:

class <class_name> {

declaration of the class;

} <object1, object2, object 3...>; OR

class <class_name> {

declaration of the class; };

void main( ) {

class_name object1, object2, ..., object n; declaration inside void main

}

10. What is the advantage of class over structure or union? Ans:

In structure/union we can’t specify the data members as private of protected. By

default the data elements are public in structure/union. So data hiding may not be possible in structures or unions.

Another problem in structure is that it doesnot allow the struct data type to be

treated like built in types. Example: struct complex { float x; float y; }; struct complex c1, c2, c3;

The complex numbers c1, c2 and c3 can easily be assigned values using the dot operator but we cannot add two complex numbers to subtract one from the other. For example: c3 = c1 + c2. Because that will be illegal in C structures.

(34)

11. What are the different access specifiers? Explain with examples.

Ans: Access specifiers are used to identify access rights for the data and member functions of the class. There are three main types of access specifiers in C++ programming language: • private

• public

• protected

Private

A private member within a class denotes that only members of the same class have accessibility. The private member is inaccessible from outside the class.

Example 16.1: class x { private: int no; void input( ) { cout<<"Enter a no"; cin>>no; } }; void main( ) { x ob;

ob.no = 20; //ERROR: Private member can't be accessed ob.input( ); //ERROR: Private member can't be accessed Public

Public members are accessible from outside the class. Example 16.2: class x { public: int no; void display( ) { cout<<no; } }; void main( ) { x ob;

(35)

ob.no=20; ob.display( ); }

Protected

A protected access specifier is a stage between private and public access. If member functions defined in a class are protected, they cannot be accessed from outside the class but can be accessed from the derived class.

Example 16.3: class x { protected: int no; void input( ) { cout<<"Enter a no"; cin>>no; } }; class y: protected x { protected: void display( ) { cout<<no; } }; void main( ) { x ob;

ob.no=11; //ERROR: The data member cannot be accessible }

12. What do you mean by C++ references? Explain with an example. Ans:

Reference variables are aliases to other variables. Any changes to the original

variable or the alias (reference variable) result in change to the same memory location.

Reference variables must always be initialized.

When pass by reference is done to functions unlike pass by value a new copy of

the variable is not created. This is very useful when big objects are passed as class members.

(36)

The other alternative is to use call by address using pointers. This involves de-referencing which may not look elegant and clean. References solve this problem. Example: Basic usage of reference variables

#include <iostream> using namespace std; int main() { int i = 100; int &j = i;

cout << "i=" << i << endl; cout << "j=" << j << endl; j += 100;

cout << "i=" << i << endl; cout << "j=" << j << endl;

cout << "Address of i=" << &i << endl; cout << "Address of j=" << &j << endl; } OUTPUT: i=100 j=100 i=200 j=200 Address of i=0012FF88 Address of j=0012FF88

13. What do you mean by array of object? Explain with an example. Ans:

If we declare array of variables for a class then it is called as array of object. Example: class employee { char name[30]; float age; public: void getdata(void); void putdata(void); };

Now for the above class we are defining the array of object. employee manager[10];

(37)

On the above there are two objects manager having size 10 and for object worker having size is 89. Hence on this example there are 99 objects for the class employee.

Example: Array of Object. #include<iostream.h> class employee { char name[30]; float age; public: void getdata(void); void putdata(void); };

void employee : : getdata(void) {

cout<<"Enter name:"; cin>>name;

cout<<"\n Enter Age"; cin>>age;

}

void employee : : putdata(void) {

cout<<"Name: "<<name<<"\n"; cout<<"Age: "<<age<<"\n"; }

const int size=3; int main( ) {

employee manager(size); for(int i=0; i<size; i++) {

cout<<"\n Details of manager"<<i+1<<"\n"; manager[i].getdata( );

}

cout<<"\n";

for(i=0; i<size; i++) { cout<<"\n Manager"<<i+1<<endl; manager[i].putdata( ); } return 0; }

(38)

14. What is an constructor? What is an default constructor? What is a parameterized constructor?

Ans:

• Constructor is a method whose name is same as class name.

• The constructor can be always declared in the public section of the area.

• Constructors are executed when we create any object of the class.

• Constructors cannot be declared as virtual or we cannot refer to their address. Default Constructor:

The constructor that has no argument is called as default constructor. Syntax is:

class <class_name> {

public:

<class_name> ( ) //constructor declaration { declaration of constructor; } }; Example: #include<iostream.h> class x { int no; public: x( ) void display( ); }; x : : x( ) { no = 10; } void x : : display( ) { cout<<no; } void main( ) { x ob; ob.display( ); } Parameterized Constructor:

(39)

Syntax is:

class <class_name> {

public:

<class_name>(arg1, arg2, ..., arg n) { declaration; } }; Example: #include<iostream.h> class x { int no; public: x( ); x(int); void display( ); }; x : : x( ) { no =10; } x : : x(int no1) { no =no1; } void x : : display( ) { cout<<no; } void main( ) { x ob;

x ob1=30; //explicit type execution x ob2(40); //implicit type execution ob.display( );

ob1.display( ); ob2.display( ); }

(40)

Ans: Dynamic initialization of object means the initial value of an object can be provided during the run time. The main advantage of the dynamic initialization of object is that we can provide the flexibility of different format of data at run time depending upon the situations. Example: dynamic initialisation of objects.

#include<iostream.h> #include<conio.h> class fixed_deposit {

long int p_amount; //principal amount int years; //period of investment float i_rate; //interest rate

float r_value; //return amount public:

fixed_deposit( ) {

}

fixed_deposit(long int p, int y, float r=0.12); fixed_deposit(long int p, int y, int r);

void display( ); };

fixed_deposit : : fixed_deposit(long int p, int y, float r) {

p_amount = p; years = y; i_rate = r;

r_value = p_amount; for(int i=0; i<=y; i++) r_value = r_value*(1.0 + r); }

fixed_deposit : : fixed_deposit(long int p, int y, int r) {

p_amount = p; years = y; i_rate = r;

r_value = p_amount; for(int i=0; i<=y; i++)

r_value = r_value*(1.0 + float(r)/100); }

(41)

fixed_deposit : : display(void) {

cout<<"\n\nPrincipal Amount = "<<p_amount<<"\t"<<"Return value="<<r_value<<endl; } void main( ) { clrscr( ); fixed_deposit fd1, fd2, fd3; long int p; int y; int R; float r;

cout<<endl<<endl<<endl<<"Enter the principal amount"; cin>>p;

cout<<"\nEnter the period"; cin>>y;

cout<<"\nEnter interest rate(in percent)"; cin>>R

fd1 = fixed_deposit(p,y,R); cout<<"\nEnter the principal amount"; cin>>p;

cout<<"\nEnter the period"; cin>>y;

cout<<"\nEnter interest rate(in decimal)"; cin>>r;

fd2 = fixed_deposit(p,y,r);

cout<<"Enter the principal amount"; cin>>p;

cout<<"Enter the period"; cin>>y; fd3 = fixed_deposit(p,y); cout<<"\n\nDeposit 1:" fd1.display( ); cout<<"\n\nDeposit 2"; fd2.display( ); cout<<"\n\nDeposit 3"; fd3.display( ); getch( ); } Output:

Enter the principal amount 10000 Enter the period 5

(42)

Enter the interest rate(in percent) 5 Enter the principal amount 10000 Enter the period 5

Enter interest rate(in decimal) 0.05 Enter the principal amount 10000 Enter the period 5

Deposit 1

Principal amount=10000 Return value=12762.81543 Deposit 2

Principal amount=10000 Return value=12762.81543 Deposit 3

Principal amount=10000 Return value=12623.417969 16. What are dynamic constructors?

Ans: While creating any object the constructor is used to allocate memory. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is known as dynamic construction object. The memory can be allocated with the help of “new” operator.

17. What do you mean by constant objects?

Ans: We can create any constant objects using “const” keyword before object declaration. For example, we may create X as a constant object of the class matrix as follows:

const matrix X(m,n); //Object X is constant Here matrix is the class name.

Any attempt to modify the values of m and n will generate compile-time error.

18. What is a destructor? Why destructor cannot be overloaded? Explain destructor with an example.

Ans:

• A destructor is a method that is declare inside a class.

• Its name is similar to a class. Its declaration is same as that of constructor but it can be defined by a tilde(~) symbol.

• It is used to destroy the object that is created by the constructor.

• A destructor never takes any argument not it return a value.

• “new” is used to allocate the memory in the constructor and we use “delete” to free that memory.

A destructor cannot be overloaded because it does not have any parameters or arguments.

(43)

Example: Destructor. #include<iostream.h> #include<conio.h> int count=0; class finish { public: finish( ) { count++;

cout<<"\n number of object created: "<<count; }

~finish( ) {

cout<<"\n number of object destroyed: "<<count; count--; } }; int main( ) { clrscr( );

cout<<"\n\n enter main\n"; finish f1, f2, f3, f4;

{

cout<<"\n\n enter block\n"; finish f5;

} {

cout<<"\n\n enter block 2\n"; finish f6;

}

cout<<"\n\n re-enter main:"; return 0;

} Output: enter main

number of object created: 1 number of object created: 2 number of object created: 3 number of object created: 4

(44)

enter block 1

number of object created: 5 number of object destroyed: 5 enter block 2

number of object created: 5 number of object destroyed: 5 number of object destroyed: 4 number of object destroyed: 3 number of object destroyed: 2 number of object destroyed: 1

19. Consider the following class F00, (for which one constructor is written). Write a destructor, a copy constructor and an assignment operator that would be appropriate for the class.

class F00 { public: int *p; F00( ): p = new int[10]; for(int k=0; k<10; k+=1) { p[k] = k; } } Ans: #include<iostream.h> class F00 { public: int *p; F00( ) { p = new int[10]; for(int k=0; k<10; k++) p[k] = k; } F00 (F00 &ob) {

(45)

p = new int[10]; for(int k=0; k<10; k++) p[k] = ob.p[k]; } ~F00( ) { delete p; } }; void main( ) { F00 ob1; F00 ob2 = ob1; }

20. Can we define more than one constructor for a class?

Ans: Yes, we can define more than one constructor for a class. This is called as multiple constructor declaration of a class.

Example: class integer { int m, n; public: integer( ) { m=0; n=0; } integer(int a, int b) { m=a; n=b; } integer(int & i) { m=i.m; n=i.n; } };

(46)

This declares the three constructors for an integer object. The first constructor receives no arguments, the two receives two integer arguments and the third receives one integer object as an argument.

21. What is the difference between constructor & destructor? Explain using example. Ans:

Constructor:

• A constructor is a special type of member function executes automatically

when an object is created. • Its syntax is:

class<class_name> { public: <class_name>( ) { statements; ... } Destructor:

• It is a special type of member function execute automatically when an

object is destroy. • Its syntax is:

class<class_name> { public: <class_name>( ) { statements; .... }

22. What do you mean by copy constructor? Explain with an example.

Ans: Copy constructor is used to declare an initialize an object from another object. The process of initializing through a copy constructor is known as copy initialization constructor. A copy constructor takes a reference to an object of the same class as itself as an

argument.

Example: Copy constructor. #include<iostream.h>

(47)

class code {

int id; public: code( ) { }

code(int a) {id =a;} code(code & x) { id = x.id; } void display(void) { cout<<id; } }; void main( ) { code A(100); code B(A); code C = A; code D; D = A; cout<<"\n id of A : " ; A.display( ); cout<<"\n id of B : " ; B.display( ); cout<<"\n id of C : " ; C.display( ); cout<<"\n id of D : " ; D.display( ); }

23. Define a class to represent a bank account with the following of data members & member function.

Data Members:-

i. Name of the customer ii. Account number iii. Type of account iv. Amount in account Member Function:-

(48)

ii. To deposit an amount iii. To withdraw an amount iv. To display name & Balance

Design the constructor(s) for the classes for the above program. Ans: #include<iostream.h> #include<conio.h> #include<string.h> class account {

char name[30]; int acc_no; char type_acc[30]; float bal; public:

void initilize(char[ ], int, char[ ], float); void deposite(int, float);

void withdraw(int, float); void display( );

account() {

cout<<"\n\t Enter name of the depositer"; cin>>name;

cout<<"\n\t Enter the account Number"; cin>>acc_no;

cout<<"\n\t Enter type of account"; cin>>type_acc;

cout<<"\n\tEnter balance"; cin>>bal;

} };

void account :: initilize(char name1[ ], int acc_no1, char type[ ], float bal1) { strcpy(name, name1); acc_no=acc_no1; strcpy(type_acc, type); bal = bal1; }

void account :: deposite(int acc_no1, float bal2) {

if(acc_no == acc_no1) bal =bal +bal2;

(49)

void account :: withdraw(int acc_no1, float bal2) { if(acc_no == acc_no1) { if(bal-bal2 > 500) { bal=bal-bal2; cout<<"Withdraw Possible"; } else

cout<<"Not sufficient balance"; }

}

void account :: display( ) {

cout<<name<<" "<<bal; }

void main( ) {

char name[30]; int acc_no; char type_acc[30]; float bal; account ob;

int i, n, ch1; clrscr( );

cout<<"\n\t 1. Deposit"; cout<<"\n\t 2. Withdraw";

cout<<"\n\t 3. Display Name and Balance"; cout<<"\n\t Enter Your Choice(1, 2 or 3)"; cin>>ch1;

switch(ch1) {

case 1:

cout<<"\n\t Enter account number deposite"; cin>>acc_no;

cout<<"\n\t Enter balance amount"; cin>>bal;

ob.deposite(acc_no, bal); break;

case 2:

cout<<"\n\t Enter account number for witdraw"; cin>>acc_no;

cout<<"\n\tEnter balance amount for withdraw"; cin>>bal;

(50)

ob.withdraw(acc_no, bal); break; case 3: ob.display( ); default: cout<<"Invalid Operations"; break; } } }

24. What do you mean by Virtual Destructor? Explain with an example.

• Virtual destructor ensures that the object destruction happens from the most derived class towards the base class.

• Significant in scenarios where derived classes object is assigned to a base class pointer.

EXAMPLE: Demonstrate the object destruction sequence.

#include <iostream.h> class Base {

public: Base() {

cout << "Base class constructor ..." << endl; }

~Base() {

cout << "Base class destructor ..." << endl; }

};

class Derived : public Base { public:

Derived() {

cout << "Derived class constructor ..." << endl; }

~Derived() {

cout << "Derived class destructor ..." << endl; }

};

void main() {

(51)

Base* base;

base = new Derived(); delete base;

}

OUTPUT:

Base class constructor ... Derived class constructor ... Base class destructor ...

25. What do you mean by inheritance? What are the types of inheritance? Explain with example.

Ans: Inheritance is the property of OOPS in which the properties of one class can be accessed by another class. The class which can access those properties are called as the derived classes and the class whose properties are derived are called as base class. Inheritance indicated to reusability of Object Oriented Programming System.

Types of Inheritance:

Inheritance is different types. Those are: The different types of inheritance are:

1. Single inheritance 2. Multiple inheritance 3. Multilevel inheritance

4. Hybrid inheritance

SINGLE INHERITANCE:

A derived class with only one base class is called single inheritance. In other words, when only one base class is used for derivation of a class and derived class is not used as base class, such type if inheritance is known as single inheritance.

MULTIPLE INHERITANCE:

Multiple inheritance is the concept where a subclass inherits properties from multiple base classes.

When a class is derived from more than one base class then that is called multiple inheritance. A familiar example of multiple inheritance is the child class inheriting the characteristics of the parents.

(52)

As for example if the class child inherits from both class father and mother, then the syntax will be:

class child : public father, public mother {

Body of the class; };

MULTILEVEL INHERITANCE:

The mechanism of deriving a class from another derived class is known as multilevel inheritance.

In this figure it is clearly explained that there is one base class and one derived class (intermediate base class). This derived class of the main base class is inherited by another class called as its derived class.

Multilevel inheritance is the collection of more than one single level inheritance.

HYBRID INHERITANCE:

The combination of one or more types of inheritance is called as hybrid inheritance.

In this figure, the class GAME is derived from two base classes LOCATION and PHYQUE. The class PHSIQUE is also derived from class PLAYER. So it is the combination of multiple and multilevel inheritance.

Example: Hybrid inheritance. #include<iostream.h> #include<conio.h> class player { protected: char name[20];

(53)

char gender; int age; };

class physique : public player { protected: float height; float weight; }; class location { protected: char city[15]; char pin[7]; };

class game : public physique, public location {

protected: char city[15]; char pin[7]; };

class game : public physique, public location { protected: char game[20]; public: void getdata( ) {

cout<<"Enter the following information\n"; cout<<"Name \n"; cin>>name; cout<<"Gender"<<endl; cin>>gender; cout<<"Age = "<<endl; cin>>age; cout<<"Height ="<<endl; cin>>height; cout<<"Weight"<<endl; cin>>weight; cout<<"City"<<endl;

(54)

cin>>city; cout<<"PIN Code"; cin>>pin; cout<<"Game"<<endl; cin>>game; void show( ) {

cout<<"\n\n\nThe entered information are"<<endl; cout<<"\n Hellow: :"<<name;

cout<<"\nYou are: "<<age<<"Years Old"; cout<<\n Your height is"<<height<<endl;

cout<<"\n Your weight is:<<weight<<"KG"<<endl; cout<<"\n Your favourite game is: "<<game; cout<<"\nYou are from: "<<city;

cout<<"\nPIN code: "<<pin; } }; void main( ) { clrscr( ); game G; G.getdata( ); G.show( ); getch( ); }

26. What do you mean by ambiguity in C++?

Ans: While using multiple inheritances, when a function with the same name appears in more than one base class then the compiler got confused to access the method. Hence ambiguity is produced. As for example: class M { public: void display(void) {

cout<<"Soumya Sourabha Patnaik\n"; }

(55)

{ public:

void display(void) {

cout<<"IACR Engineering College\n"; }

};

class P : public M, public N { public: void display(void) { M : : display( ); } int main( ) { P p;

p.display( ); //faces ambiguity }

27. How ambiguity can be produced due to single inheritance? Explain with an example. Ans: If the same function can be defined in both the classes then ambiguity can be

produced. Example: class A { public: void display( ) {

cout<<"Soumya Sourabha Patnaik\n"; } }; class B: public A { public: void display( ) {

cout<<"IACR Engineering College\n"; }

References

Related documents

The main activity of Innobuzz is providing training in Information Security, which is delivered to its audience all over the world via Computer Based Training Courses, Onsite

In weighing the evidence, the Panel took into account that consumption of non-digestible carbohydrates results in reduced post-prandial blood glucose (and

Customer relationship has been regarded as the most important issue of the firms, so that an attempt is made to develop customer relationships and their comments on quality and

Recorded on the estimate sheet are material costs, labor costs, overhead costs, contingency costs, and profit. Numerous mathematical calculations need to be performed to determine

For Advertising call 617-779-3771 Pilot Bulletins Saint Mary of the Annunciation, Cambridge, MA 4468.. “God is Love”1

This email contains contact details for the Chief Investigator, and has a link to a Lancaster university website where individuals can access a copy of the participant information

Process Boundary (Multiple Process Model) Interface Layer Server Layer Application Layer Storage Layer RequestComponent ResponseComponent SessionComponent UserComponent

By leveraging various forms of capital and learning to straddle multiple cultures, rural students can go beyond simply enrolling in higher education and make both their