Object Oriented Programming With c++ (Hanumanth Ladwa)
Object Oriented Programming With c++ (Hanumanth Ladwa)
PROGRAMMING WITH
HANUMANTH LADWA
Dedicated to
My parents
And
My sisters
Contents
Chapter Page
Chapter Title
no. no.
1 Introduction to C++ 1 – 25
2 C++ data types 26 – 30
3 I/O Operators 31 – 35
Selection and looping
4 36 – 68
statements
5 Arrays 69 – 80
Built-in and user defined
6 81 – 102
functions
7 Function overloading 103 – 109
8 Function templates 110 - 124
9 Pointers 125 – 137
10 Structures and unions 138 - 154
11 Classes 155 – 174
12 Constructors and destructors 175 – 190
13 Operator overloading 191 - 207
14 Class template 208 – 218
15 Inheritance 219 - 252
Polymorphism and virtual
16 253 – 268
functions
17 File handling 269 - 281
The called procedure may have another procedure call that creates a
hierarchy of procedure calls as shown in the diagram below.
The main program may call procedure 1 but procedure 1 has a call of
procedure 2 and vice versa. Similarly, the main program may call procedure 2
but procedure 2 has a call of procedure 3 and vice versa. Because one
procedure is embedded in another procedure increases complexity and as the
program grows, increases the complexity of the program. It does not model
real world objects.
Object Oriented Programming: programmers developed a new
programming language called Object Oriented Programming (OOP) to
overcome the drawbacks of procedural oriented programming. C++ was
developed by Bjarne Stroustrup at AT & T bell laboratory, New Jersey, USA
in the early 1980. C++ is defined as a superset of C. Earlier C++ was called C
with classes. The name C with classes was renamed as C++ by Rick Mascitti
in 1983. Some of the programming languages that uses OOPs concept are,
C++, VC++, C#, Java, Simula 67 etc.
Let us understand the terminologies used in procedural oriented programming
and object-oriented programming.
Data members
Rollno.
Name
percentage
Function
members
getdata()
putdata()
Disadvantages of OOPs
- OOP software is not having set standards.
- The adaptability of flow diagrams and object-oriented programming using
classes and objects is a complex process.
- To convert real world problem into an object-oriented model is difficult.
- The classes are overly generalized.
Applications of OOP:
- Computer graphic applications.
- CAD/CAM software.
- Object oriented databases.
- User interface design such as windows.
- Real-time systems.
- Simulation and modelling.
- Artificial intelligence and expert systems.
- Hypermedia, expert text and hypertext.
- Decision support systems and office automation systems.
- Parallel programming and neural networks.
Characteristics of C++:
- Object oriented programming: each problem is viewed as an object
to solve. We mimic the real-world entities into object-oriented
programs to solve the given problems. But it is not possible to convert
the real-world objects into object-oriented programs as it is.
- Portability: it is possible to execute the code written in C++ in any
type of computer and operating system without making any changes.
- Brevity: code written in C++ is short in comparison with other
programming languages.
- Modular programming: C++ uses a modular approach by dividing
the problem into small logical components that performs a specific
task, each module can be written, tested and debugged separately and
linked together while executing. Thus, it saves time.
- C compatibility: C++ is backward compatible with the C language.
Any program written in C can easily be included in a C++ program
without making any change.
- Speed: once the C++ source program is compiled, the compiler
generates an object code present in the .obj file. This code is very
efficient.
- Machine independent: C++ is not dependent on machine hardware
(architecture) or software (operating system).
- Flexibility: C++ is a very versatile and flexible programming
language.
- Wide range of library functions: C++ has a huge collection of built-
in functions that reduces code development time and cost of software
development.
- System software development: As C++ is a middle level language
used for both application software and system software. It helps to
develop systems software such as, operating system, compiler, loader,
macros, assembler etc.
Character set of C++: every programming language has its own set of
characters to form the lexical units. The character set includes letters, digits
and special symbols.
Letters: A – Z (Upper case alphabets) and a – z (Lower case alphabets).
Digits: 0 – 9
Special symbols: , . ?/”{}[]=+-* etc.
C++ programming language is capable of processing any of the 256 ASCII
(American Standard Code for Information Interchange) characters.
Tokens: token is a smallest or basic unit of a program. All the programming
languages are made up of these lexical elements. C++ programming language
has the following tokens.
- Identifiers
- Keywords
- Constants
- Operators
Identifiers: identifier is a name given to the programming elements such as,
arrays, functions and variables. Identifiers can contain letters, digits and
underscore. C is case sensitive, hence uppercase and lowercase letters are
distinct.
Rules for writing identifiers:
- Identifiers must begin with a – z (lowercase letter) or A – Z (uppercase
letter) or _ (underscore).
- Keywords should not be used as an identifier name.
- Uppercase and lowercase letters are different.
For example, marks are different from MARKS.
- No special characters are allowed except _ (underscore).
- The identifier name must be of some reasonable length.
Following are the some of the valid and invalid identifier names,
Valid identifiers: marks, roll_no, _name, student123, etc.
Invalid identifiers:
123name //starts with digit
roll-no //special character hyphen is used
int // keywords are not allowed
keywords: keyword is a predefined word that has fixed meaning to the
compiler that cannot be changed by the programmer. These are the reserved
words that are already defined within the compiler, and the compiler
identifies it as a keyword. All keywords should be written in lowercase letters
only. Some of the keywords are listed below.
if break for do while goto else int
char float double void case const continue
default return unsigned signed short long sizeof
switch typedef union auto volatile enum
Constants:
The quantity or value that does not change during execution of the program is
called constant.
Integer constants: these are the whole numbers without any decimal point.
Integer constants are prefixed with plus or minus sign. Further integer
constants are classified as decimal constants, octal constants, hexadecimal
constants and unsigned constants.
Decimal constants: these are the constants whose base or radix of the
number system is 10. Decimal constants range from 0-9. Any big number can
be generated that consists of a combination of digits between 0 to 9.
Example, 123, -410 etc are decimal constants.
Octal constants: these are the constants whose base or radix of the number
system is 8. Octal constants range from 0-7. Any number generated must
have digits between 0-7 and octal constants always begin with 0.
Example, 0345, -0145
0825 // this integer is an invalid octal number because 8 is not an octal digit
Hexadecimal constants: these are the constants whose base or radix of the
number system is 16. Hexadecimal range from 0 – 9 and a – f or A – F.
hexadecimal digits a (or A) through f (or F) represent value from 10 through
15. Any number generated must be between the range of 0 – 9 and a (or A)
through f (or F) and hexadecimal constants prefixed with 0x or 0X.
Example, 0x8FFFAD, -0X3ADEF etc.
Unsigned constants: to specify an unsigned type we use either u or U suffix.
To specify a long type, we use either l or L suffixes.
Example, 478u; // unsigned constant
0x7777ffL // hexadecimal long type
07524ul //octal unsigned long type
Floating-point constants: these are the constants with the decimal point and
fractional part are called floating point constants. Floating-point constants are
also called real numbers. These constants can be represented in two forms,
- Fractional form
- Mantissa exponent form
Fractional form: fractional form of floating-point numbers can be
represented as integer part followed by decimal point followed by fractional
part.
Example, 20.05
20 . 05
Integer part Decimal point Fractional part
Mantissa exponent notation: any big number or any small number can be
written in the form of power of 10.
Example,
4.523e2 // 4.523 x 102
4.523E-2 // 4.523 x 10-2
-0.4523e-2 // -0.4523 x 10-2
The exponent may be specified using e or E followed by an optional sign (+
or -) and a sequence of digits.
Character constants: a single character enclosed within a pair of single
quotation marks.
For example, ‘a’, ‘@’, ‘&’ etc.
Each of these characters are assigned with the integer constant values called
ASCII (American Standard Code for Information Interchange) values
standardized by ANSI (American National Standard Institute). For example,
ASCII value of A is 65, B is 66 and so on Z is 90 (uppercase letters), a is 97,
b is 98 and so on z is 122 (lowercase letters), 0 is 48, 1 is 49 and so on 9 is 57
(digits).
There is another class of character, which are non-printable, but they have
special meaning. For example, space bar, tab button, enter button, back space
etc. such character constants are called escape sequences. This type of
character constants is always used with the output statements and these types
of constants begin with \ (backslash).
Following table shows the list of escape sequences used in C,
Escape sequence Description
\a system alarm (beep)
\b Backspace
\f Form feed
\n New line (line feed)
\r Carriage return
\t Horizontal tab
\v Vertical tab
\” Double quote
\’ Single quote (apostrophe)
\0 Null character (end of string)
\\ Backslash itself
Relational operators:
The relational operators supported by C are: ==, !=, >, >=, <, <=
Let us consider, a=10 and b=20 then:
Operator Description Example
== Compares the values of (a==b) return false
two operands equal or
not
!= Compares the values of (a!=b) return true
two operands equal or
not
> Checks if the value of (a>b) return false
the operand on the left
is greater than the right
operand.
< Checks if the value of (a<b) return true
the operand on the left
is less than the right
operand.
>= Checks if the value of (a>=b) return false
the operand on the left
is greater than or equal
to the right operand.
<= Checks if the value of (a<=b) return true
the operand on the left
is less than or equal to
the right operand.
Logical AND: the result of the logical AND is true, when both the operands
are true; otherwise the result is false.
Operand1 Operand2 Operand1&&Operand2
False False False
False True False
True False False
True True True
Logical OR: the result of the logical OR is false, when both the operands are
false; otherwise the result is true.
Operand1 Operand2 Operand1||Operand2
False False False
False True True
True False True
True True True
Logical NOT: the result of the logical NOT is true when the operand is
false and vice versa.
Operand !Operand
False True
True False
Bitwise operators: these operators work on bits. The truth table of some of
the bitwise operators is as follows:
a&b (bitwise a|b (bitwise a^b (bitwise
a b
AND) OR) XOR)
0 0 0 0 1
0 1 0 1 0
1 0 0 1 0
1 1 1 1 1
The bitwise operators supported by C++ are listed in the following table:
Operator Description Example
& Binary AND return bit 1 if both operands a&b=0000 1010
bits are 1, otherwise 0.
| Binary OR return bit o if both operands bits a|b=0000 1011
are 0, otherwise 1.
^ Binary eXclusive OR (XOR) returns bit 0 if a^b=0000 1110
there are odd numbers of 1’s. Otherwise 1.
~ Binary negation complements the bits. ~a=0000 0101
Converts bits 1 to 0 and vice versa.
<< Binary left shift operator shifts the number a<<2=0010 1000
of bits specified onto the left.
>> Binary right shift operator shifts the number a>>2=0000 0010
of bits specified onto the right.
Let us consider, a=10 and b=11 then converting into binary,
a=0000 1010 b=0000 1011
The result of bitwise ANDing of a and b is,
a = 0000 1010
b = 0000 1011
a&b = 0000 1010
the result of bitwise ORing of a and b is,
a = 0000 1010
b = 0000 1011
a|b = 0000 1011
the result of bitwise eXclusive-ORing of a and b is,
a = 0000 1010
b = 0000 1011
a^b = 0000 1110
the result of bitwise complement of a is,
a=0000 1010
~a=1111 0101
The left shift bitwise operator changes the content of the operand by shifting
the number of bits specified from left.
General form:
Operand left_shift_operator number_of_bits
Example: a<<2
The result of the bitwise left shift operator is,
Before left shifting of bits
0 0 0 0 1 0 1 0
After two bits shifted to left
0 0 1 0 1 0 0 0
The right shift bitwise operator changes the content of the operand by shifting
the number of bits specified from right.
General form:
Operand right_shift_operator number_of_bits
Example: a>>2
The result of the bitwise right shift operator is,
Before right shifting of bits
0 0 0 0 1 0 1 0
After two bits shifted to right
0 0 0 0 0 0 1 0
Shorthand assignment operators:
Shorthand assignment operators are a compact way of writing assignment
statements in an expression. The shorthand assignment operator works on
both arithmetic operators and bitwise operators.
The general form of a shorthand assignment operator is,
Operand operator=expression
The following table shows the use of assignment operators:
Operator Assignment statements Shorthand assignment
+ (plus) a=a+b a+=b
- (minus) a=a-b a-=b
* (multiplication) a=a*b a*=b
/ (integer division) a=a/b a/=b
% (modular division) a=a%b a%=b
& (bitwise AND) a=a&b a&=b
| (bitwise OR) a=a|b a|=b
^ (bitwise XOR) a=a^b a^=b
<< (bitwise left shift) a=a<<b a<<=b
>> (bitwise right shift) a=a>>b a>>=b
Ternary operator: these are the operators that operate on three or more
operands. The symbol ? is used as a ternary operator. the general form of a
ternary operator is,
Expression ? value1 : value2;
Precedence or hierarchy of operators:
The order in which the expression is evaluated is called precedence of the
operator. It is also called the priority of operators.
For example, 2-3*4 can be evaluate the value -10, not -4 because, the
operator * has high priority than – hence, first 3*4 will be evaluated and then
subtracted from 2. Hence, we get the result of this expression as -10.
The following table shows the priority and associativity of the operators:
Operator category Operators Precedence Associativity
Parentheses, braces (), [] 1 L to R
Unary operators -, ++, --, !, ~, & 2 R to L
Multiplicative operators *, /, % 3 L to R
Additive operators +, - 4 L to R
Shift operators <<, >> 5 L to R
Relational operators <, <=, >, >= 6 L to R
Equality operators ==, != 7 L to R
Bitwise operators &, ^, | 8 L to R
Logical operators &&, || 9 L to R
Conditional operators ?, : 10 R to L
Assignment operators =, +=, -=, *=, /=, 11 R to L
%=, ^=, |=, <<=,
>>=
Comma operator , 12 L to R
Character functions: all the character functions are present in the ctype.h
header file. The following table shows some of the functions present in the
ctype.h header file.
Function Meaning
isalpha(c) It returns true if c is an alphabet,
otherwise false.
isdigit(c) It returns true if c is a digit,
otherwise false.
isalnum(c) It returns true if c is alphabet or
digit, otherwise false.
islower(c) It returns true if c is lowercase letter,
otherwise false
isupper(c) It returns true if c is uppercase letter,
otherwise false
toupper(c) It converts lowercase letters to
uppercase letters.
tolower(c) It converts uppercase letters to
lowercase letters.
String functions: the string manipulation functions are present in a string.h
header file. Some of the functions are listed in the table below.
Function Meaning
strlen(s) It returns the number of characters
present in the string including blank
spaces.
strcat(s1,s2) This function combines or
concatenates two strings together.
String 2 concatenates at the end of
string 1.
strcpy(s1,s2) It copies the string 2 to string 1
strcmp(s1,s2)==0 It compares s1 and s2 and finds out
strcmp(s1,s2)>0 whether s1 equal to s2, s1 greater
strcmp(s1,s2)<0 than s2 or s1 less than s2
strcmpi(s1,s2)==0 It compares s1 and s2 ignoring case
strcmpi(s1,s2)>0 and finds out whether s1 equal to s2,
strcmpi(s1,s2)<0 s1 greater than s2 or s1 less than s2
strrev(s) It reverses a string
strupr(s) It converts string into upper case
strlwr(s) It converts string into lower case
Console I/O functions: some of the functions present in the conio.h header
file are listed in the table below.
Function Meaning
getch() It is used to retain the output on the
console till the user presses any
button.
getche() It is used to retain the output on the
console till the user presses any
button the value of the character
returned from getche().
EXERCISES
1. Explain the programming techniques.
2. What are the terminologies used in procedure-oriented
programming and object-oriented programming?
3. What is the difference between procedure-oriented programming
and object-oriented programming?
4. Briefly explain the concepts of OOP.
5. Write the advantages of OOP.
6. Describe the disadvantages of OOP.
7. Mention the applications of OOP.
8. What are the characteristics of C++?
9. Mention the character set of C++.
10. What is a token? Mention the types of tokens.
11. What is an identifier? State the rules for declaring identifiers.
12. Define keywords with examples.
13. What are constants? Mention its types.
14. Define character constant. Give an example.
15. What is string constant? Mention an example.
16. What are operators? Explain with examples.
17. Explain increment and decrement operators with an example.
18. What are arithmetic operators? Explain with examples.
19. What are relational operators? Explain with examples.
20. Describe the logical operators with an example for each.
21. Explain bitwise operators with examples.
22. What are ternary operators? Explain with an example.
23. What is the hierarchy of operators? Explain with an example.
24. Describe type conversion. Name its types.
25. Explain the structure of C++ program.
26. Name some header files used in C++.
27. Explain any five character functions with examples.
28. Describe any five string functions with examples.
29. Explain I/O functions.
CHAPTER 2
C++ DATA TYPES
Introduction: C++ provides a rich set of data types to handle the data used
by the program. It is categorized as, primitive data types, derived data types
and user defined data types. Data types indicate the type of data that the
variable can hold.
Variables: a variable is a quantity that changes during execution of the
program. C++ encourages us to use meaningful names for variables.
Variables are declared in the declaration section before using them in the
program. In C++ program, the variable represents the memory location that
holds the value assigned to it.
Declaration of a variable: the syntax for declaring a variable is,
Data_type variable_name;
Here, the variable_name is the identifier name that must satisfy all the rules
for declaring an identifier. The variables are named storage locations whose
values can be manipulated during program execution.
Some valid variables:
Roll_no data date_of_birth percentage
Some invalid variables:
float //it is a keyword
total_% //special symbol % is not allowed
2subjects //started with the digit
My result //blank space is not allowed
Initializing a variable:
The general form of initializing a variable is,
Data_type variable_name=value;
Example: int a=10;
Here, int is one of the primitive data types. And a is a variable that holds
integer type of data. The variable a is a named storage location. 10 is a
constant value assigned to the variable a of type integer. A semicolon
indicates termination of variable declaration.
How to make a value of the variable constant?
Example, int a=10;
In this example, the variable a is of type integer with value 10 is assigned to it
can be changed at any point of time. In order to make it constant we use a
keyword const before the data types as follows:
const int a=10;
now, the value of the variable a is constant, that cannot be changed during the
program execution.
Derived data types: derived data types are created using fundamental data
types. They include arrays, functions, pointers and references. The details
about these concepts will be covered in the forthcoming chapters.
User defined data types: user defined data types are also constructed using
fundamental data types. They include structure, union, class and enumeration.
Now we will learn enumerated types of data. We will learn in detail about
structure, union and class in later chapters.
Enumerated data type: it is an user defined data type consisting of a set of
named constants called enumerators. enum is a keyword that assigns values
0, 1, 2, … automatically.
The general form of enum is as follows:
enum[tag]{enum-list};
Example 1: enum ratings{very_bad,bad,good,better,best}; // definition of
enum type
ratings myrate; //declaration of variable of type ratings
example 2: enum rays{alpha,beta,gamma};
Here in this example, alpha takes value 0, beta takes value 1 and gamma
takes value 2.
We can also change the default values to any user defined values.
Example 3: enum shirtsize{small=10, medium=20,large=30};
Here in this example small takes value 10, medium takes value 20 and large
takes value 30.
EXERCISES
1. What are data types? Classify them.
2. Describe a variable with its declaration and initialization.
3. Explain basic data types with an example for each.
4. What are modifiers? Mention its types.
5. Explain enumerated data type with an example.
CHAPTER 3
I/O OPERATORS
Introduction: Program written in C, takes one or more input data and output
information. There are two methods of writing programs, one is a non-
interactive way where variables are initialized. Another is an interactive way
where the program will interact with the user to enter some data through the
keyboard. Inputting data is done through keyboard and the processed data i.e.
information will be displayed on to the monitor.
The input output operation can be performed by using the objects cin and
cout present in iostream.h class. Using these two objects, we will be able to
interact with the user by printing messages on the screen and getting input
from the user through the keyboard.
C++ uses the data input and output in the form of stream. That is, a stream is
a flow of bytes from input device to output device and vice-versa.
Input operator “>>”
Input in C++ is done by using stream extraction (>>) on the cin stream. The
operator must be followed by the variable that will store the data that is going
to be extracted from the stream.
Ex: int regno;
cin>>regno;
The first statement in example declares the variable of type int called regno,
and the second one waits for an input from cin in order to store it in this
integer variable. cin stands for console input.
Output operator “<<”
Outputting in C++ is done by using stream insertion (<<) on the cout stream.
cout stands for console output.
Ex: cout<<”Let us learn C++ programming”;
Notice that the sentence in the instruction is enclosed between double quotes
(“), because it is a string constant.
// Write a program to find the sum of 2 numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y,sum;
clrscr();
cout<<"Enter two numbers:\n";
cin>>x>>y;
sum=x+y;
cout<<"The sum of "<<x<<" and "<<y<<" = " <<sum;
getch();
}
Output:
Enter two numbers:
3
2
The sum of 3 and 2 = 5
I/O Cascading:
C++ supports the use of stream extraction (>>) and stream insertion (<<)
operators many times in a single input (cin) and output (cout) statements. If a
program requires more than one input variable then it is possible to input
these variables in a single cin statement using multiple stream extraction
operators. Similarly, when we want to output more than one result then this
can be done using a single cout statement with multiple stream insertion
operators. This is called the cascading of input output operators.
Ex: cout<<”enter the value of x”;
cin>>x;
cout<<”enter the value of y”;
cin>>y;
instead of using cin statement twice, we can use a single cin statement and
input the values for the two variables x and y using multiple stream extraction
operator as shown below,
cout<<”enter the value for x and y”;
cin>>x>>y;
similarly, we can even output multiple results in a single cout statement using
cascading of stream insertion operator as shown below,
cout<<”the sum of ”<<x<<” and ” <<y<<” = “ <<x+y;
// Write a program to create simple calculator
#include<iostream.h>
#include<conio.h>
void main()
{
int a, b, sum, diff, prod, quot, rem;
cout<<"Enter two numbers:\n";
cin>>a>>b;
sum=a+b;
diff=a-b;
prod=a*b;
quot=a/b;
rem=a%b;
cout<<"Sum="<<sum<<"\nDifference="<<diff<<"\nProduct="
<<prod<<"\nQuotient="<<quot<<"\nRemainder="<<rem;
getch();
}
Output:
EXERCISES
1. What are the input and output operators? Explain with a neat
diagram.
2. What is an input output cascading? Explain an example.
3. Write a program to find the sum of two numbers.
4. Write a program to create a simple calculator.
5. Write a program to convert seconds into hours, minutes and
seconds.
6. Write a program to compute simple interest.
7. Write a program to calculate compound interest.
8. Write a program to find the area of a cube, cuboid, cylinder.
9. Write a program to convert Fahrenheit temperature into Celsius.
10. Write a program to find the volume of a square, cone, rectangle.
CHAPTER 4
SELECTION AND LOOPING
STATEMENTS
Introduction: in general, instructions written are executed in a linear fashion
called sequential order. It is not mandatory that all the instructions are to be
executed in the order in which they are written, in some situations, the control
may bifurcate based on the condition, some statements get executed
repeatedly a certain number of times based on the condition. Some statements
may jump from one statement to another based on the condition imposed.
C++ provides two types of control statements:
- selection statements
- iterative statements
Selection statements: Selection statements are also called conditional control
statements used to check the condition, based on the condition, the control
makes decision and branching.
There are four types of selections statements,
i. if-statement
ii. if-else statement
iii. nested statement
iv. switch statement
if statement: if statement is also called a one-way branching statement. In
simple if statements, if the condition is true then the statement or set of
statements will get executed. If the condition is false then the next statements,
if any, will get executed.
The general form of if statement is,
if(condition) OR if(condition)
statement1; {
statement1;
statement2;
…
statement-n
}
// Write a program to display the class obtained by the student
#include<iostream.h>
#include<conio.h>
void main()
{
float percentage;
clrscr();
cout<<"Enter the percentage: ";
cin>>percentage;
if(percentage>35)
cout<<"PASS";
getch();
}
Output:
Enter the percentage: 62
PASS
run 2:
Enter the age of a person: 17
You are not eligible for voting
run 1:
Enter the number: 5
The number 5 is odd
run 2:
Enter the number: 10
The number 10 is even
run 2:
Enter the percentage: 80
First class
run 3:
Enter the percentage: 55
Second class
run 4:
Enter the percentage: 42
Pass class
run 5:
Enter the percentage: 33
Fail
run 1:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 2:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 3:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 4:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 5:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 6:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 7:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 8:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red
run 1:
Enter the gender (M/F): m
Enter the age: 38
You are eligible to marry
run 2:
Enter the gender (M/F): m
Enter the age: 20
You are not eligible to marry
run 3:
Enter the gender (M/F): f
Enter the age: 18
You are eligible to marry
run 4:
Enter the gender (M/F): f
Enter the age: 17
You are not eligible to marry
switch statement: it is an alternative of if-else-if ladder. It is used to select
one block of code if the expression present in the switch statement matches
with the case label. Here switch expression will hold only one of the three
values, int, char or Boolean values. This statement provides multiple way
branching.
The general form of switch statement is,
switch(expression)
{
case label-1: statement 1;
break;
case label-2: statement 2;
break;
…
case label-n: statement n;
break;
default: default-statement;
}
The break statement is used to indicate that the case label is terminated. The
default statement will get executed if the switch expression does not match
with any case label.
run 1:
Enter two numbers:
2
3
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
run 3:
Enter two numbers:
3
5
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
run 5:
Enter two numbers:
5
6
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
run 6:
Enter two numbers:
4
5
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
run 1:
Enter the number: 3
It is a prime number
run 2:
Enter the number: 6
It is not a prime number
exit() function: break statement was used to exit out of the looping and
switch statements, but exit() function, present in the stdlib.h header file is
used to terminate the entire program.
The general form of exit() function is,
exit();
/* write a program to check whether a given number is prime or not
using exit() function */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i;
clrscr();
cout<<"Enter the number: ";
cin>>n;
for(i=2;i<=n/2;++i)
if(n%i==0)
{
cout<<"It is not a prime number";
exit(0);
}
cout<<"It is a prime number";
getch();
}
Output:
EXERCISES
1. Write a program to find the sum and average of n numbers.
2. Define an array. Explain its types.
3. How to declare a one-dimensional array? Explain with an example.
4. Explain the initialization of a one-dimensional array.
5. How to declare a two-dimensional array? Explain with an example.
6. Explain the initialization of a two-dimensional array.
7. Write a program to find the position of an element in an array.
8. Write a program to sort elements of an array.
9. Write a program to find the transpose of a matrix.
10. Write a program to find the sum of compatible matrices.
11. Write a program to find the product of compatible matrices.
12. Write a program to find the row and column sum of two-
dimensional arrays.
13. Write a program to find the sum of principal diagonal elements.
14. Write a program to check the frequency of a number in a 2-
dimensional array.
CHAPTER 6
BUILT-IN AND USER DEFINED
FUNCTIONS
Introduction:
When the program is lengthy and complex, the program has to be divided
into a number of small logical components that perform a specific task. This
finite set of instructions that performs a specific task is called module or sub
program.
Types of functions:
- library functions
- user-defined functions
Library functions: The functions which are already defined within the
compiler are called Library functions. These functions are present in the
header files that the user needs to include in his/her program.
Header files:
Different header files are used in C programs to meet the needs of the
programmer. Some of the header files and the functions present in them are
listed as below.
stdio.h header file: this is a standard input output header file used to perform
input and output operations using built-in functions. Some of the built-in
functions present in this header file are listed below.
printf, scanf , getchar, gets, putchar, puts etc.
string.h header file: this header file is used to manipulate string. Some of the
built-in functions present in this header file are listed below.
strcmp, strcat, strcmpi, strcpy, strlen, strlwr, strupr, etc.
stdlib.h header file: this is a standard library header file. Some of the built-in
functions present in this header file are listed below.
free, malloc, calloc, realloc, exit etc.
iostream.h header file: this is the input output stream header file. Some of
the built-in functions present in this header file are listed below.
open, close, get, getline, read, write, put, seekg, tellg, seekp, tellp, eof etc.
math.h header file: this header file contains mathematical functions. Some
of the built-in functions present in this header file are listed below.
cos, sin, tan, sqrt, abs, fabs, exp, pow, log etc.
character and string functions: a character constant is any letter, digit or
special symbol enclosed within a single pair of quotation marks. To perform
any operation on characters we have to include the ctype.h header file. Some
of the built-in functions present in this header file are listed below.
function description example
isalpha() It returns 1 if the isalpha(‘A’) returns 1
character is alphabet, isalpha(‘5’) returns 0
otherwise, it returns 0
isdigit() It returns 1 if the isdigit(‘A’) returns 0
character is digit, isdigit(‘5’) returns 1
otherwise, it returns 0
isalnum() It returns 1 if the isalnum(‘H’) returns 1
character is alphabet or isalnum(‘6’) returns 1
digit, otherwise, it isalnum(‘?’) returns 0
returns 0
isupper() It returns 1 if the isupper(‘K’) returns 1
alphabet is upper case, isupper(‘p’) returns 0
otherwise, it returns 0
islower() It returns 1 if the islower(‘K’) returns 0
alphabet is lower case, islower(‘p’) returns 1
otherwise, it returns 0
isspace() It returns 1 if the isspace(‘ ‘) returns 1
character is blank, isspace(‘\n’) returns 1
otherwise, it returns 0 isspace(‘J’) returns 0
ispunct() It returns 1 if the ispunct(‘#’) returns 1
character is a special ispunct(‘3’) returns 0
symbol, otherwise, it
returns 0
toupper() It converts lowercase toupper(‘a’) returns A
letter to uppercase
tolower() It converts uppercase tolower(‘A’) returns a
letter to lowercase
toascii() It converts the toascii(‘A’) returns 65
characters into its
ASCII value.
Inputting single character: we can input a single character using the get()
function as below.
char ch;
ch=cin.get();
Outputting single character: we can output a single character using the
put() function as below.
char ch;
ch=cin.get();
cout.put(ch);
// write a program to read and write a character
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
clrscr();
cout<<"Enter the character: ";
ch=cin.get();
cout<<"Inputted character is ";
cout.put(ch);
getch();
}
Output:
Enter the character: K
Inputted character is K
Note: After executing the program press Alt+F5 to see the output in Turbo
C++ compiler.
String functions: string constants are the sequence of characters enclosed
within a pair of double quotation marks. Manipulation on strings is
performed by built-in functions present in the string.h header file. String is an
array of characters.
Declaration:
Syntax:
char array_name[size];
Example:
char s[20];
Initializing a string:
Example 1: char s[10]=”Programming”;
Here, 11 characters are present in Programming. The null character (\0) is
automatically inserted at the end of the string by the compiler.
Example 2: the string can also be initialized character-wise without
specifying its size.
char s[]={‘P’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0’};
Inputting a string: to input a string, C++ provides a function called
getline().
The general form is,
cin.getline(string,size);
Example:
char str[20];
cin.getline(str,20);
Outputting a string: to output a string, C++ provides a function called write.
The general form is,
cout.write(string,size);
Example:
char str[20];
cout.write(str,20);
// Write a program to input and output a string
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
cout<<"Enter the string: ";
cin.getline(str,20);
int l=strlen(str);
cout<<"Entered string is: ";
cout.write(str,l);
getch();
}
Output:
Enter the string: Hanumanth
Entered string is: Hanumanth
Note: After executing the program press Alt+F5 to see the output in Turbo
C++ compiler.
strlen() function: this function is used to return the total number of
characters present in the entered string. It returns an integer number
indicating the length of the string.
Syntax: variable=strlen(string);
Example: int l=strlen(“Programming”) returns 11
strcat() function: this function is used to combine two strings together. This
function is used to concatenate string2 to string1. The process of combining
two strings together.
Syntax: strcat(string1,string2);
Example: char s1[10]=”Lot”;
char s2[10]=”us”;
strcat(s1,s2);
here, string 2 appends at the end of string1 and it returns Lotus.
strcpy() function: this function is used to copy string2 in place of string1.
String1 will be replaced by string2.
Syntax:
strcpy(string1,string2);
Example: char s1[10]=”Lotus”;
char s2[10]=”Lilly”;
strcpy(s1,s2);
This returns Lilly.
strcmp() function: this function is used to compare a string alphabetically.
This function is case sensitive. i.e. both uppercase and lowercase letters are
different.
Syntax:
strcmp(string1,string2);
Example:
char s1[]=”Hello”;
char s2[]=”hello”;
strcmp(s1,s2) returns -1
strcmp(s2,s1) returns 1
if both the strings are equal then it returns 0.
strcmpi() function: this function is used to compare a string alphabetically.
This function is case insensitive. i.e. both uppercase and lowercase letters are
the same. If string1>string2 then it returns 1, if string1<string2 then it returns
-1, if string1 is equal to string2 then it returns 0.
Syntax:
strcmpi(string1,string2);
Example:
char s1[]=”Hello”;
char s2[]=”hello”;
strcmpi(s1,s2) returns 0
User-defined functions: the function defined by the user to solve his/her
problem is called user-defined function. In a user defined function, the user
uses his/her logic to solve a particular problem.
Advantages of user-defined functions:
- If there is a set of statements to be repeated several times in the
program, these statements can be replaced as a function and called
whenever and wherever required.
- A function can be developed and made available to more than one
program or to a group of programmers.
- Functions developed can be tested and debugged independently.
- If a program is divided into small modules, each module can be
developed by an individual programmer.
- If functions are developed, the number of lines of code decreases in
the program.
Syntax of user-defined function:
Where, return_type is the data type used to return a value by the function. if
nothing is returned to the calling function, then data type is void.
function_name is any valid identifier name that follows all the rules of
identifier. argument_list_with_declaration is used to declare all the variables
that receive value from the calling function (i.e. main() function). Local
variable declarations are the variables that are accessed within the function
definition. Executable statements perform necessary operations to solve
problems. If the function has a return type other than void then
return(expression) is needed.
// write a program to find the sum of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int a, int b); //function prototype
int a,b,sum;
clrscr();
printf(“Enter two numbers:\n”); calling function
scanf(“%d%d”,&a,&b);
sum=add(a,b); // function call
printf(“Sum=%d”,sum);
getch();
}
EXERCISES
1. What are functions? Mention their types.
2. What is the difference between built-in function and user defined
function?
3. Explain any five header files.
4. Describe any five functions of ctype.h header.
5. Write a program to convert lowercase letters to uppercase letters.
6. Describe any five string functions with an example for each.
7. Write a program to find the length of the string.
8. Write a program to concatenate two strings.
9. Write a program to determine whether the string is palindrome.
10. Write a program to find the number of vowels and consonants in an
entered string.
11. Explain the advantages of user-defined functions.
12. What is a user defined function? Write its syntax.
13. Write a program to find the greatest of three numbers.
14. Write a program to find the square of a number.
15. Explain default arguments with programming examples.
16. Write a program to find the factorial of a number.
17. Explain types of arguments.
18. Write a program to concatenate two strings
19. Describe the use of scope of a variable with a programming
example.
CHAPTER 7
FUNCTION OVERLOADING
Introduction: we have learnt about polymorphism. Let us recall it once
again, poly means many, morph means forms. polymorphism means many
forms. The ability of the message to process in more than one form is called
polymorphism. The best examples for polymorphism are function
overloading and operator overloading. In this chapter we will learn function
overloading, in the forthcoming chapter we will learn operator overloading.
Definition: two or more functions having the same name with different
return type or different number of arguments. Function overloading is used in
a situation where, similar operation is to be performed on different types of
data. When an overloaded function is invoked, the C++ compiler chooses the
appropriate function by examining the number, data types and order of
arguments present in the function call. Function overloading can also be
defined as two or more functions having different return types with different
signatures. The signature means, function name followed by the parameter
list as shown below.
#include<iostream.h>
#include<conio.h>
int area(int a);
int area(int l, int w);
double area(double b, double h);
void main()
{
clrscr();
cout<<"Area of square="<<area(5)<<endl;
cout<<"Area of rectangle="<<area(5,10)<<endl;
cout<<"Area of triangle="<<area(2.0,3.0);
getch();
}
int area(int a) // area of a square
{
return(a*a);
}
int area(int l,int w) // area of a rectangle
{
return(l*w);
}
double area(double b,double h)
{
return(0.5*b*h);
}
Output:
Area of square=25
Area of rectangle=50
Area of triangle=3
// Write a program to find the biggest of set of parameters
#include<iostream.h>
#include<conio.h>
int big(int a, int b);
float big(float x, float y, float z);
double big(double p, double q, double r);
void main()
{
clrscr();
cout<<"Biggest of integer="<<big(15,23)<<endl;
cout<<"Biggest of floating-point="<<big(5.25,4.42,2.26)<<endl;
cout<<"Biggest of double-precision="<<big(6.36,2.3,3.3)<<endl;
getch();
}
int big(int a, int b)
{
if(a>b)
return a;
else
return b;
}
float big(float x, float y, float z)
{
float big=x;
if(y>big)
big=y;
if(z>big)
big=z;
return big;
}
double big(double p, double q, double r)
{
double big=p;
if(q>big)
big=q;
if(r>big)
big=r;
return big;
}
Output:
Biggest of integer=23
Biggest of floating-point=5.25
Biggest of double-precision=6.36
Inline functions: a function call involves the complex process of invoking a
function, passing parameters to the function, allocating storage for local
variables, thereby using extra time and memory space. It is possible to avoid
these overheads of a function by using an inline function.
Definition: inline function is a compact function call that replaces the
function call by function definition. The keyword inline is used to define an
inline function.
// Write a program to find a cube of a number
#include<iostream.h>
#include<conio.h>
inline int cube(int a)
{
return(a*a*a);
}
void main()
{
int n;
clrscr();
cout<<"Enter the number: ";
cin>>n;
cout<<"Cube of a number="<<cube(n);
getch();
}
Output:
Enter the number: 5
Cube of a number=125
Advantages of inline functions:
- The inline functions are compact function calls. Therefore, the size of
the object code is considerably reduced.
- The speed of execution of a program increases.
- Very efficient code can be generated.
- The readability of the program increases.
Disadvantages:
- As the body of the function is substituted in place of function call, the
size of the executable file size increases.
- Inline function occupies more memory.
- If there is any change in inline function then the function call this
inline function has to be recompiled.
When not to use inline function: an inline function should not be used in a
situation where,
- Inline function definition is too long or too complicated.
- The inline function is recursive.
- The inline function has looping constructs.
- The inline function has a switch or goto statements.
EXERCISES
1. What is function overloading? Give an example.
2. Write the advantages of overloaded functions.
3. Restrictions on overloaded functions.
4. Write a program to find the sum of different types using function
overloading.
5. Write a program to find the area of a square/rectangle/triangle
using function overloading.
6. Write a program to find the biggest of set of parameters
7. Explain what are inline functions.
8. Write a program to find a cube of a number
9. Write a program to find a square of a number
10. What are the advantages of inline functions?
11. What are the disadvantages of inline functions?
12. When not to use inline functions?
13. Write a program to find the largest of two numbers using an inline
function.
CHAPTER 8
FUNCTION TEMPLATES
Introduction: In the previous chapter we have learnt how to overload
functions. There is a disadvantage of using function overloading. Overloaded
functions perform similar operations on different data types. For this we have
to write separate code for each function definition. This creates an extra effort
for the programmers. This extra effort of writing similar functions again and
again we can use the new feature of C++ called function templates.
Definition: A function template is a method of writing a single generic
function for a group of similar functions designed to handle different data
types.
General form of function template:
template <class T> T function_name (T parameters)
{
//Function body with parameter type T
}
Where, T is a template parameter, class T is a template type parameter
enclosed with the angular braces (< >). class and template are keywords.
In order to find the greatest of numbers of different types using function
overloading can be written as follows:
int max(int x, int y)
{
return (x>y)?x:y;
}
float max(float x, float y)
{
return(x>y)?x:y;
}
double max(double x, double y)
{
return(x>y)?x:y;
}
char max(char x, char y)
{
return(x>y)?x:y;
}
There are disadvantages of writing similar functions with different data types
again and again. These are,
- Writing similar functions with different data types again and again is a
time-consuming process.
- Writing similar functions, they occupy more amount of storage space.
- When the error creeps in we have to correct it in the rest of the
functions.
In order to overcome these disadvantages, we use function templates, as
shown below.
template <class T>
T max (T x, T y)
{
return (x>y)?x:y;
}
Where T is the template parameter. This parameter is not necessarily T only,
you can write any identifier name for this parameter.
You can observe here, there is no specific data type. How does the compiler
select a particular function? When a template creates a specific type, a built-
in or user defined data type is substituted is called template instantiation.
/* Write a program to find the maximum of two numbers using a
function template. */
#include<iostream.h>
#include<conio.h>
template <class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
void main()
{
clrscr();
cout<<"Max(10,15)="<<max(10,15)<<endl;
cout<<"Max(10.25,15.75)="<<max(10.25,15.75)<<endl;
cout<<"Max('A','a')="<<max('A','a')<<endl;
cout<<"Max(25.235645,20.124587)="<<max(25.235645,20.124587)<<endl;
getch();
}
Output:
Max(10,15)=15
Max(10.25,15.75)=15.75
Max('A','a')=a
Max(25.235645,20.124587)=25.235645
Here, the function call max(10,15) makes the compiler select the function
max(int,int) to invoke, the function call max(10.25,15.75) makes the
compiler select the function max(float,float) to invoke. Similarly, done with
other types.
// Write a program to swap two data items of type int, float and double
#include<iostream.h>
#include<conio.h>
template <class T>
T swap(T &x, T &y)
{
T temp;
temp=x;
x=y;
y=temp;
return(0);
}
void main()
{
int a,b;
float p,q;
double m,n;
clrscr();
cout<<"Enter two integers: \n";
cin>>a>>b;
cout<<"Before interchanging: a="<<a<<" and b="<<b<<endl;
swap(a,b);
cout<<"After interchanging: a="<<a<<" and b="<<b<<endl;
getch();
}
Output:
Enter two integers:
2
4
Before interchanging: a=2 and b=4
After interchanging: a=4 and b=2
Enter two floating-point numbers:
2.35
5.55
Before interchanging: p=2.35 and q=5.55
After interchanging: p=5.55 and q=2.35
Enter two double precision numbers:
12.22345
19.45365
Before interchanging: m=12.22345 and n=19.45365
After interchanging: m=19.45365 and n=12.22345
// Write a program to sort array elements using function template
#include <iostream.h>
#include<conio.h>
template<class T>
void sort(T a[ ])
{
int i,j;
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
if(a[i]>a[j])
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
for(i=0;i<5;i++)
cout<<a[i]<<endl;
cout<<endl;
}
void main( )
{
int intarray[5]={20, 10, 50, 40, 30};
float floatarray[5]={1.6, 2.0, 4.1, 1.8, 2.8};
char chararray[5]={'c','a','d','e','b'};
clrscr();
cout<<"SORTED INTEGER ARRAY"<<endl;
sort(intarray);
cout<<"SORTED FLOAT ARRAY"<<endl;
sort(floatarray);
cout<<"SORTED CHAR ARRAY"<<endl;
sort(chararray);
getch();
}
Output:
SORTED INTEGER ARRAY
10
20
30
40
50
EXERCISES
1. What is a function template? Explain with a programming
example.
2. Explain template argument deduction with an example.
3. Describe explicit template arguments with an example.
4. Briefly explain template inclusion compilation model
5. Explain separation compilation model with example.
6. Describe overloading function templates.
7. What is overload resolution with instantiation? Explain with a
programming example.
CHAPTER 9
POINTERS
Introduction: Till now we have studied how to declare variables of different
types. We know how many bytes that each type takes in memory, but we do
not know how these variables are stored in memory. The computer’s memory
is viewed as a consecutive block of locations identified by a unique number
called address. How we have got house numbers in a street, in a similar
fashion memory is organised. Everything we declare stores in a particular
memory location. Each data stored in memory location can be accessed by its
address.
Definition: a pointer is a special variable that holds the address of other
variables, structures and functions. It holds only the memory address of the
variable.
Advantages of pointers:
- With the help of pointers, efficient programs can be written.
- Memory is utilised properly.
- Allocate and deallocate memory at run-time (Dynamic).
- Easy to deal with hardware components of the computer.
- Pointer establishes the communication between program and data.
Pointer declaration: we have studied that the memory is organised in a
consecutive way. In order to understand pointers, we need to first understand
the organization of memory locations. Memory is organized as an array of
bytes. Each byte is identified by a unique number called address. Suppose we
have 1KB of memory then 1KB=1024 bytes, each byte is organized in a
sequential order with the subscript from 0 to 1023. The 0th subscript
represents the first memory location whereas the 1023rd subscript represents
the last memory location.
There are two operators used with pointers,
The address operator: & (ampersand).
The indirection operator: * (asterisk).
The address operator returns the address of the variable whereas the
indirection operator returns the content stored in the address.
When we declare a pointer variable with these two operators as,
int a, *iptr;
iptr=&a;
here, a and *iptr are common variable and pointer variable (any variable
preceded by *). In the second statement the address of a variable a is equated
to iptr.
If we initialize a variable with value as,
int a=10, *iptr;
iptr=&a;
then the same is represented in memory as follows,
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
void swap(int,int);
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before swapping a="<<a<<" and b="<<b<<endl;
swap(a,b);
getch();
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"After swapping a="<<a<<" and b="<<b;
}
Output:
Enter two numbers:
100
200
Before swapping a=100 and b=200
After swapping a=200 and b=100
When we pass references as arguments to the function, the function receives
the lvalue to these arguments rather than their actual values as in call by value
method. This helps the function to note down the memory location of the
argument and can take the address of the argument or modify its value.
/* Write a program to swap two numbers using call by reference with
reference arguments*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
void swap(int &,int &);
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before swapping a="<<a<<" and b="<<b<<endl;
swap(a,b);
getch();
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"After swapping a="<<a<<" and b="<<b;
}
Output:
Enter two numbers:
250
500
Before swapping a=250 and b=500
After swapping a=500 and b=250
Memory allocation of pointers:
There are two ways to allocate memory to pointers,
- Static memory allocation
- Dynamic memory allocation
Static memory allocation: in this allocation, the amount of memory to be
allocated is predicted and pre known. This memory is allocated during the
compilation itself. All the declared variables declared normally, are allocated
memory statically.
Example, int a; /* this declaration of a variable a allocates 2 bytes of
memory at compile time*/
Dynamic memory allocation: in dynamic memory allocation, the amount of
memory to be allocated is not known. This allocation can be done at time of
execution.
We can allocate and deallocate memory location for the object at run time
using new and delete operators respectively. These operators allocate
memory for objects from a pool called free store. The object allocated
memory using the new operator should be deleted using the delete operator.
Otherwise, it results in memory leak.
To allocate memory of type integer,
int *iptr=new int;
OR
int *iptr;
iptr=new int;
To allocate memory for array,
int *iptr=new int[20];
To allocate memory for structure,
student *sp=new student;
// Write a program to demonstrate dynamic memory allocation
#include<iostream.h>
#include<conio.h>
int *ptr;
void fun()
{
ptr=new int;
*ptr=10;
}
void main()
{
clrscr();
fun();
cout<<"Value of *ptr="<<*ptr;
getch();
}
Output:
Value of *ptr=10
In this program, memory allocated is not deleted. Hence, it creates orphaned
memory block that lead to adverse effects on the system.
delete the object allocated memory dynamically as,
delete object_name;
example,
delete ptr;
To delete array, delete [] iptr;
To delete structure, delete sp;
// Write a program to illustrate the use of new and delete operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int *iptr=new int(10);
float *fptr=new float(2.25);
char *cptr=new char('H');
cout<<"Integer value is "<<*iptr<<endl;
cout<<"Floating-point value is "<<*fptr<<endl;
cout<<"Character value is "<<*cptr<<endl;
delete iptr;
delete fptr;
delete cptr;
getch();
}
Output:
Integer value is 10
Floating-point value is 2.25
Character value is H
Free store: it is a pool of unallocated memory used to allocate to a program
dynamically at run-time.
This free memory is also called heap memory, which is reserved to use only
at run-time allocation.
Memory leak: if the variables, that are allocated memory dynamically, are
not freed by using the operator delete, the memory block remains occupied
even after the program execution terminates. Such memory blocks are known
as orphaned memory blocks. These orphaned memory blocks, when
increased in number, bring adverse effects on the system. This situation is
called memory leak.
/* write a program to sort elements of an array in an ascending order
using dynamic memory allocation*/
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n, j, temp;
clrscr();
cout<<"How many elements?";
cin>>n;
int *a=new int[20];
cout<<"Enter the elements:\n";
for(i=0;i<n;i++)
cin>>*(a+i);
cout<<"The sorted elements are\n";
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
for(i=0;i<n;i++)
cout<<a[i]<<endl;
getch();
}
Output:
How many elements?5
Enter the elements:
30
50
10
40
20
The sorted elements are
10
20
30
40
50
EXERCISES
1. What is a pointer? Write its advantages.
2. Mention the operators used with pointers.
3. Write a program to display the value and address of a variable.
4. Explain operation performed on pointers.
5. Describe pointer initialization with programming examples.
6. How is memory allocated dynamically in C++?
7. Write a program to sort elements of an array using dynamic
memory allocation technique.
8. Write a program to find the location of an element in an array
using a pointer.
CHAPTER 10
STRUCTURES AND UNIONS
Introduction: Till now we have studied variables of simple types like, int,
char, float and double. Variables of these types represent one item of
information such as, a mark, an account, a height etc. In order to collect such
variables together we use structures. We have studied arrays; arrays are
collections of Homogeneous types of data under the same name. But
structures are collections of Heterogeneous data items under the same name.
structures are exactly opposite to that of arrays, because arrays are collections
of similar types whereas, structures are collections of different types.
Consider a situation where we want to process the information of an
employee, where we process the data such as employee code, salary, name,
designation etc. All these data are of different types, employee code is of int,
salary is of float, and name and designation are of type char. Hence, in order
to process more than one type of data structures are used.
Definition: A structure is a collection of the same or different simple
variables. Some variables can be int, some can be float and so on. The data
items in a structure are called members of the structure. Once the structure is
defined, the user-defined data type is defined.
Syntax of structure:
struct structure_name
{
Data_type1 member_name-1;
Data_type2 member_name-2;
…
Data_type-n member_name-n;
};
Where, structure definition begins with the keyword struct followed by
structure_name that is a valid identifier name given to the structure, that
obeys all the rules of defining identifier. Curly open brace indicates the
beginning of the body of structure definition. Under the curly open brace
collection of data members are declared with their types. Curly closing brace
and semicolon indicate that this is the termination point of structure
definition.
Structure definition serves as a blueprint or template, which does not
hold any space in memory of a computer system. Once the structure is
defined, you can create any number of variables (or objects) of that type.
Each object occupies the memory space (memory space depends on the
number of variables declared in the structure definition and how many bytes
each variable takes).
Let us consider an example of structure definition,
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
};
student s1,s1,s3;
The above structure definition consists of four members, rollno int type,
name char type holds 20 characters, combination char type holds 4 characters
and percentage float type. As we already know that, int takes 2 bytes, char
takes 1 byte, float takes 4 bytes of memory. Once we create variables s1,s2,s3
and so on, of student type, each variable takes 30 bytes of memory space. The
following diagram depicts how memory is allocated to each element.
/* Write a program to show the number of bytes each object takes in
structure*/
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
}s1;
clrscr();
cout<<"The size of object s1="<<sizeof(s1);
getch();
}
Output:
The size of object s1=30
Accessing the elements of a structure:
The members of the structures can be accessed using dot operators. it is not
possible to access the members of the structure directly. Instead you can
access members of the structure as, structure variable (or object) followed by
dot operator and followed by member name.
Structure_variable.member_name;
The dot operator is also called a member access operator.
In the above example, if we wish to access rollno, it is accessed for the first
object as, s1.rollno. Similarly, name can be accessed as, s1.name and so on.
// write a program illustrate the use of dot operator
#include<iostream.h>
#include<conio.h>
void main()
{
struct test
{
int a;
int b;
}t;
clrscr();
t.a=10;
t.b=20;
cout<<"The value of a="<<t.a<<endl;
cout<<"The value of b="<<t.b;
getch();
}
Output:
The value of a=10
The value of b=20
Note: here, in the above example, object t is declared soon after the curly
closing brace of the class definition. Each member a and b are accessed using
the dot operator.
// write a program to read and write the information of a student
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
};
struct student s1;
clrscr();
cout<<"Enter the roll number: ";
cin>>s1.rollno;
cout<<"Enter the name of the student: ";
cin>>s1.name;
cout<<"Enter the combination: ";
cin>>s1.combination;
cout<<"Enter the percentage: ";
cin>>s1.percentage;
cout<<"Roll number="<<s1.rollno<<endl;
cout<<"Name of the student="<<s1.name<<endl;
cout<<"Combination="<<s1.combination<<endl;
cout<<"Percentage="<<s1.percentage<<endl;
getch();
}
Output:
Enter the roll number: 1
Enter the name of the student: Hanumanth
Enter the combination: pcmc
Enter the percentage: 80.33
Roll number=1
Name of the student=Hanumanth
Combination=pcmc
Percentage=80.330002
Initializing a structure: the structure can be initialized as follows,
employee e={
10,
“Hanumanth”,
“CEO”,
50000000.00
};
Similarly, a student structure definition can also be initialized as,
student s1={
1,
“Priyanka”,
“PCMC”,
77.20
};
Embedded structures: A structure within another structure is called
embedded structure. It is also called nested structures. The embedded
structure declared first and the outer structure declared next.
Example 1:
struct distance
{
int feet;
float inches;
};
struct room
{
distance length;
distance breadth;
};
The structure room contains another structure, distance. i.e. the structure
distance is enclosed within the room structure. The definition of structure
distance precedes the definition of the structure room.
Example 2:
struct date
{
int day;
int month;
int year;
};
struct employee
{
int empid;
date doj;
float salary;
}e;
To access the member empid, we write, e.empid. To access the member day,
month and year of date of joining (doj), we write, e.doj.day, e.doj.month and
e.doj.year respectively. To access the member salary, we write, e.salary.
// write a program to receive and display the information of an employee
#include<iostream.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
void main()
{
struct employee
{
int empid;
struct date doj;
float salary;
}e;
clrscr();
cout<<"Enter the employee id: ";
cin>>e.empid;
cout<<"Enter the Date of Joining: ";
cin>>e.doj.day>>e.doj.month>>e.doj.year;
cout<<"Enter the salary: ";
cin>>e.salary;
cout<<"Employee Information\n";
cout<<"Employee id="<<e.empid<<endl;
cout<<"Employee Date of Joining="<<e.doj.day<<"-"<<e.doj.month<<"-"
<<e.doj.year<<endl;
cout<<"salary="<<e.salary;
getch();
}
Output:
Enter the employee id: 100
Enter the Date of Joining: 14 06 2021
Enter the salary: 100000
Employee Information
Employee id=100
Employee Date of Joining=14-6-2021
salary=100000
Array of structures: Till now we have studied how to process one or more
object’s data but in order to process huge data, we require the use of arrays.
When we want to process, say, 1000 employees’ information, we cannot
create individual objects like e1,e2,…e1000. It is very cumbersome, instead
we can use an array of structure, where we create a huge number of objects
by simply writing the array size as below.
struct employee
{
int empid;
char name[20];
char designation[15];
float salary;
}e[1000];
Here, e is an array of 1000 elements. Each element of the array e is a separate
structure of type employee.
e[0].empid access the employee id of the first employee. Whereas,
e[1000].empid access the employee id of the 1000th employee. The same is
depicted in the following diagram.
Employee Information
---------------------------------------
empid name designation
---------------------------------------
1 Swaroop Cashier
2 Raj Manager
---------------------------------------
Type definition (typedef):
The keyword typedef is used to alias the data types. That is, giving one more
name to the data types. It creates synonyms for the data types.
Syntax:
typedef old_data_type new_data_type;
Here, typedef is a keyword used to alias the data type. old_data_type may be
basic or user defined or derived data types. new_data_type is any user
defined valid identifier name.
Example 1: typedef int wholeno;
Here, int is an old data type whereas, wholeno is a new data type.
Example 2: typedef float realno;
Here, float is an old data type whereas, realno is a new data type.
Similarly, we can also give aliasing names to the structure.
Example:
struct employee
{
int empid;
char name[20];
float salary;
};
typedef struct employee my_staff;
Here, employee is an old data type whereas, my_staff is a new data type.
With the help of new data type, we can create objects as,
my_staff Ramesh;
Here, my_staff is acting as a data type which is employee type and Ramesh is
an object of type my_staff.
// write a program to demonstrate the use of typedef
#include<iostream.h>
#include<conio.h>
void main()
{
struct author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
};
typedef struct author book_writer;
book_writer bw;
clrscr();
cout<<"Enter the number of books published: ";
cin>>bw.no_of_books;
cout<<"Enter the name of the author: ";
cin>>bw.author_name;
cout<<"Enter the name of the publisher: ";
cin>>bw.publisher;
cout<<"Enter the price of the book: ";
cin>>bw.price;
cout<<"------------------------------------------------------\n";
cout<<"\t\tBook Information\n";
cout<<"------------------------------------------------------\n";
cout<<"Number of books: "<<bw.no_of_books<<endl;
cout<<"Author name: "<<bw.author_name<<endl;
cout<<"Publisher: "<<bw.publisher<<endl;
cout<<"Price: "<<bw.price<<endl;
cout<<"------------------------------------------------------\n";
getch();
}
Output:
Enter the number of books published: 8
Enter the name of the author: Hanumanth
Enter the name of the publisher: Self
Enter the price of the book: 600
------------------------------------------------------
Book Information
------------------------------------------------------
Number of books: 8
Author name: Hanumanth
Publisher: Self
Price: 600
------------------------------------------------------
Array of structure initialization:
Array of structure can also be initialized in the following way,
struct student
{
int rollno;
char name[20];
float percentage;
};
stud s[]={
1, “Priyanka”, 77.25,
2, “Sneha”, 50.00,
3, “Soniya”, 65.33,
4, “Swaroop”, 45.00,
5, “Raj”, 42.66,
6, “Rakshita”, 93.00,
};
Here, s is an array of structures whose size is not specified. The values
initialized will define the size, here, 6 students’ information is provided
hence, the size of the array is 6. The amount of memory occupied depends on
the number of objects initialized.
Unions: Union is also a collection of heterogeneous elements, similar to
structures. But there is a difference between how structure members and
union members store. Each member of a structure is assigned its own
memory location. Whereas, all union members share a common memory
location. Thus, unions are used to save memory.
Syntax of union definition:
union union_name
{
Data_type1 member_name-1;
Data_type2 member_name-2;
…
Data_type-n member_name-n;
};
Here, union is a keyword, union_name is a valid identifier name, data_type1,
data_type2…data_type-n are types of data and member_name-1,
member_name-2,… member_name-n are variables.
Example:
union author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
}a;
Accessing union members:
Accessing union members is similar to accessing structure members using
dot operators. Even the arrow (->) operator can be used. In the above
example, we can access each member by using dot operator as,
a.no_of_books;
a. author_name;
a. publisher;
a.price;
Here, a is an object that holds the memory space of the maximum size of
member declared in a union. In the above example, no_of_books occupies 2
bytes, author_name occupies 20 bytes, publisher occupies 15 bytes, prince
occupies 4 bytes. The maximum amount of memory is occupied by the
author_name variable because its size is 20 which is maximum among all
other variables present in the union. Hence, the size of the object is 20 bytes
in this example.
// Write a program to return the size of union object
#include<iostream.h>
#include<conio.h>
void main()
{
union author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
}a;
clrscr();
cout<<"The size of the union object a is "<<sizeof(a)<<" bytes";
getch();
}
Output:
The size of the union object a is 20 bytes
EXERCISES
1. Write a difference between arrays and structures.
2. Write the syntax of defining structure.
3. Write a program to accept rollno, name, combination and
percentage of a student and print the same.
4. Explain how to initialize structure.
5. What are nested structures? Explain with an example.
6. Describe an array of structures with a programming example.
7. Write a program to accept empid, name, designation and compute
gross salary of the employee. (Hint: Gross salary=basic+da+hra).
8. What is union? Explain how union is different from structure.
9. Write a program to accept and display the information of 100
students.
10. Write a program to accept the information of a teacher such as,
name, designation, department, qualification and process the data
and print the same.
CHAPTER 11
CLASSES
Introduction: Every problem in an Object-Oriented Programming is viewed
as an object rather than procedure. Real world objects can be represented as
data variables. Data variables can be identified as rollno, percentage,
attendance etc. When these real-world objects are represented as data in
computers, they can also be manipulated or processed by using functions in
C++. For instance, rollno of a student can be updated, the percentage of
marks can be calculated and so on. To combine the data variables i.e. objects
along with appropriate functions for manipulation of these objects, the
concept of classes was introduced in object-oriented programming.
The concept of object-oriented programming begins with the use of classes
and objects. A class creates a new data type. It is a collection of both data and
functions in a single unit. We have studied the concept of combining data
elements into a group called structure in the previous chapter. The data
elements in a class are called data members and functions are called as
function members of the class.
Class definition: class is a fundamental building block of object-oriented
programs. It consists of both data and functions that operate on these data. A
class is a collection of objects of similar types. A class is a user-defined data
type.
The general form of a class is,
class class_name
{
private: data_member;
function_member;
public: data_memeber;
function_member;
protected: data_member;
function-member;
};
The class head is made up of the keyword class followed by the name of the
class. Class body is enclosed within the curly open and close brackets. The
class body consists of both data members and function members. The class
definition is terminated by a semicolon. The class name is any valid identifier
name that satisfies all the rules for writing identifier names. class is a
keyword and it should be written in lowercase letters only.
There are three member access specifiers, viz, private, public and protected.
All of these three are keywords.
Example:
class student
{
private: int rollno;
char name[20];
float percentage;
public: void getdata();
void putdata();
};
Here, the class name student is a new type identifier that is used to declare an
instance of that class type. The class contains three data members (rollno,
name, percentage) and two function members (getdata() and putdata()).
Data members are declared under private access specifiers whereas member
functions are declared under public access specifiers. If no member access
specifier is specified, by default it is private. The function members getdata()
and putdata() are used to write instructions to perform operations on member
data. These two member functions only can provide access to get member
data from outside the class. Therefore, the data cannot be accessed by any
other function that is not the member of the class.
Once the class is defined, we can create any number of objects of class type,
because class is user defined data type. Each object created is separated by a
comma.
Accessing members of the class:
The members of a class can be data or function members. The public data
members of the class can be accessed with the help of member access
operator dot(.) operator.
The general form for accessing members of the class is,
class_object.data_member;
class_object.function_member(arguments);
Let’s learn an example of defining a class and its object.
// Write a program to find the sum of two numbers
#include<iostream.h>
#include<conio.h>
class example
{
int a,b;
public: void getdata()
{
cout<<"Enter two numbers:\n";
cin>>a>>b;
}
void putdata()
{
cout<<"Sum of two numbers: "<<(a+b);
}
};
void main()
{
example e;
clrscr();
e.getdata();
e.putdata();
getch();
}
Output:
Enter two numbers:
2
4
Sum of two numbers: 6
Here, a and b are data members declared without access specifiers. That is,
both a and b are private members of the class by default. The function
member getdata() and putdata() are used to receive and display the sum of
two numbers. The function members getdata() and putdata() are user-defined
functions. You can write any valid identifier names to the user-defined
functions. And e is an object of type example. We can access members of the
class as, observe in main() function, object e is followed by dot(.) operator
followed by getdata(). Similarly, object e is followed by dot (.) operator
followed by putdata(). Execution of C++ programs starts from main()
function only. At least and at most one main() function must be present in a
C++ program. When the compiler encounters with the statement e.getdata();
the compiler searches for the function definition and it executes all the
instructions present in it and then control transfers back to main() function’s
next statement, when the compiler encounters with the statement e.putdata();
the compiler searches for the function definition and it executes all the
statements present in it and then control transfers back to main() function
once again, then it terminates. If you are eager to see the flow of control that
jumps from one place to another, then you press the F7 function button (in
Turbo C++ compiler) to trace the program flow.
// Write a program to process student information
#include<iostream.h>
#include<conio.h>
class student
{
private: int rollno;
char name[20];
float percentage;
public: void getdata()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the percentage: ";
cin>>percentage;
}
void putdata()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name="<<name<<endl;
cout<<"Percentage="<<percentage<<endl;
}
};
void main()
{
student s;
clrscr();
s.getdata();
s.putdata();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Hanumanth
Enter the percentage: 80.33
Roll number=1
Name=Hanumanth
Percentage=80.330002
Significance of access specifiers:
An object is defined to be an instance of a class. Every member of a class is
specified by three levels of access protection for providing security to the
data. The access specifiers define the scope of data. In C++ there are three
types of access specifiers,
- private
- public
- protected
private: A member data can only be accessed by the member function.
members declared under private are accessible only within the class. If no
access specifier is mentioned, by default, members are private.
Example: private: int a,b;
public: Members declared under public can be accessed by any function
outside the class definition.
Example:
// Write a program to demonstrate the use of public access specifiers.
#include<iostream.h>
#include<conio.h>
class room
{
int height;
public: int length, breadth;
void set_height(int a)
{
height=a;
}
int put_height()
{
return height;
}
};
void main()
{
room r;
clrscr();
r.length=5;
r.breadth=10;
r.set_height(15);
cout<<"Length="<<r.length<<endl;
cout<<"Breadth="<<r.breadth<<endl;
cout<<"Height="<<r.put_height()<<endl;
getch();
}
Output:
Length=5
Breadth=10
Height=15
protected: Members declared under protected can be accessed by the
member functions, friend function and the members of the derived class
(Inheritance) . We will study Inheritance
in detail in the forthcoming chapter.
Example:
// Write a program to demonstrate the use of protected access specifiers.
#include<iostream.h>
#include<conio.h>
class room
{
protected: double width;
};
class smallroom:room
{
public: void getdata(double w)
{
width=w;
}
double putdata()
{
return width;
}
};
void main()
{
smallroom r;
clrscr();
r.getdata(5.0);
cout<<"Width of room: "<<r.putdata();
getch();
}
Output:
Width of room: 5
Here, protected member width from class room is accessible within another
class called smallroom. The room is a base class and smallroom is a derived
class. The room class inherits properties to the smallroom class.
Member functions: Member functions can be defined inside the class
definition as well as outside the class definition.
- Inside class definition
- Outside class definition
Member function inside class definition: we have already learnt how to
define member function inside the class definition. Let us learn one more
programming example that shows how to define member functions inside the
class definition.
/* Write a program to find the area of a rectangle by defining member
functions inside the class definition. */
#include<iostream.h>
#include<conio.h>
class rectangle
{
int length, breadth;
public: void input_data()
{
cout<<"Enter the length and breadth:\n";
cin>>length>>breadth;
}
int compute_area()
{
return(length*breadth);
}
void output_data()
{
cout<<"Area of a rectangle="<<compute_area();
}
};
void main()
{
rectangle r;
clrscr();
r.input_data();
r.output_data();
getch();
}
Output:
Enter the length and breadth:
10
5
Area of a rectangle=50
Function definition outside the class definition: function can be declared
and it can be defined outside the class definition using scope resolution (::)
operator.
The general form for writing function definition outside the class definition
is,
return_type class_name::member_function(arg1, arg2,…,arg-n)
{
Function body;
}
/* Write a program to perform arithmetic operations by defining
functions outside the class definition. */
#include<iostream.h>
#include<conio.h>
class arithmetic
{
float a,b;
public: float sum(float a, float b);
float diff(float a, float b);
float prod(float a, float b);
float div(float a, float b);
};
float arithmetic::sum(float a, float b)
{
return(a+b);
}
float arithmetic::diff(float a, float b)
{
return(a-b);
}
float arithmetic::prod(float a, float b)
{
return(a*b);
}
float arithmetic::div(float a, float b)
{
return(a/b);
}
void main()
{
arithmetic ar;
float a,b;
clrscr();
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Sum="<<ar.sum(a,b)<<endl;
cout<<"Difference="<<ar.diff(a,b)<<endl;
cout<<"Product="<<ar.prod(a,b)<<endl;
cout<<"Division="<<ar.div(a,b)<<endl;
getch();
}
Output:
Enter two numbers:
20
5
Sum=25
Difference=15
Product=100
Division=4
Array of objects: we know that, once we define a class, we can create any
number of objects of that type. If we have a huge number of objects to be
created and process the data, in such a situation we use an array of objects.
An array having class type is called an array of objects.
// Write a program to show the use of array of objects
#include<iostream.h>
#include<conio.h>
class student
{
int rollno,m1,m2,m3;
public: float avg();
void receive();
void display();
};
void student::receive()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the subject 1 marks: ";
cin>>m1;
cout<<"Enter the subject 2 marks: ";
cin>>m2;
cout<<"Enter the subject 3 marks: ";
cin>>m3;
display();
}
float student::avg()
{
return(m1+m2+m3)/3.0;
}
void student::display()
{
cout<<"Percentage="<<avg()<<endl;
}
void main()
{
student s[3]; // array of objects
clrscr();
for(int i=0;i<3;i++)
s[i].receive();
getch();
}
Output:
Enter the roll number: 1
Enter the subject 1 marks: 66
Enter the subject 2 marks: 80
Enter the subject 3 marks: 75
Percentage=73.666664
Enter the roll number: 2
Enter the subject 1 marks: 55
Enter the subject 2 marks: 50
Enter the subject 3 marks: 51
Percentage=52
Enter the roll number: 3
Enter the subject 1 marks: 45
Enter the subject 2 marks: 87
Enter the subject 3 marks: 80
Percentage=70.666664
Here, the receive() function member has display() function call. Hence, the
control transfers to display() function. The display() function has an avg()
function call. The control transfers to avg() function and it returns the average
value of three subject marks to the display() function. Then the control
transfers back to the main() function and then it repeats the same procedure
for next two students' information.
Objects as function arguments: A function can receive an object as a
function argument. It is similar to any other data type being sent as a function
argument.
/* Write a program to demonstrate the use of objects as function
arguments. */
#include<iostream.h>
#include<conio.h>
class sum
{
int a,b;
public: void getdata()
{
cout<<"Enter the value of a and b:\n";
cin>>a>>b;
}
void putdata(sum x,sum y)
{
int c;
c=x.a+y.b;
cout<<"Sum of "<<a<<" and "<<b<<"="<<c;
}
};
void main()
{
sum s;
clrscr();
s.getdata();
s.putdata(s,s);
getch();
}
Output:
Enter the value of a and b:
5
5
Sum of 5 and 5=10
friend function: We learnt that private and protected members of a class
cannot be accessed from outside the class in which they are declared. In some
situations where two classes must share a common function. C++ allows the
common function to be shared between the two classes by making the
common function as a friend to both the classes, hence allowing the function
to have access to the private data of both of these classes.
A friend function is a non-member function that is a friend of a class. The
friend function is declared within a class with the prefix friend. But it should
be defined outside the class like a normal function without the prefix friend.
It is just like a friend(s) who is using your books, pencil and other
belongings.
// Write a program to show the use of a friend function
#include<iostream.h>
#include<conio.h>
class data
{
int a,b;
public: void getdata(int i, int j);
friend int sum(data d);
};
void data::getdata(int i,int j)
{
a=i;
b=j;
}
int sum(data d)
{
return(d.a+d.b);
}
void main()
{
data obj;
clrscr();
obj.getdata(20,40);
cout<<"Sum="<<sum(obj);
getch();
}
Output:
Sum=60
Remember the following points while using the friend function.
- A friend function is a non-member function that has full access rights
to the private and protected members of the class.
- It cannot be called using the object of that class. It can be invoked like
any normal function.
- It can be declared anywhere and it is not affected by the access
specifiers (private, public and protected).
- Friend functions are normal external functions that are given special
privileges.
- It cannot access the member variables directly and has to use an object
name. member name.
- The friend function is declared with the friend keyword. But while
defining it should not use either friend keyword or :: operator.
Nested classes: A class can be enclosed within another. It is similar to the
nested structures.
// Write a program to illustrate the use of nested classes
#include<iostream.h>
#include<conio.h>
class student
{
int rollno;
char name[20];
float per;
public: class date
{
int day,month,year;
public: void set_date(int dd, int mm, int yy)
{
day=dd;
month=mm;
year=yy;
}
void displaydate()
{
cout<<"Date of birth="<<day<<"-"<<month<<"-"<<year<<endl;
}
};
void input_data()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the percentage: ";
cin>>per;
}
void output_data()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name of the student="<<name<<endl;
cout<<"Percentage="<<per<<endl;
}
};
void main()
{
int d,m,y;
student s;
clrscr();
student ::date dob;
s.input_data();
cout<<"Enter the date of birth:\n";
cin>>d>>m>>y;
cout<<"Student\'s information is as follows\n";
s.output_data();
dob.set_date(d,m,y);
dob.displaydate();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Hanumanth
Structure Class
Defined with the keyword struct Defined with the keyword class
Members are public by default. Members are private by default.
Contains data members and
Contains only data members.
function members.
Enter the percentage: 78
Enter the date of birth:
1
1
1990
Student's information is as follows
Roll number=1
Name of the student=Hanumanth
Percentage=78
Date of birth=1-1-1990
Here, we have created the object for the nested class as student ::date dob.
Difference between structure and class:
EXERCISES
1. Define class with its syntax and an example.
2. Explain the member access specifiers used in C++.
3. Describe how to access members of the class.
4. Write a program to show how to define a function definition
outside the class definition.
5. Describe array objects with a programming example.
6. Explain how to pass objects as function arguments.
7. Write a program to illustrate the use of nested classes.
8. What is the difference between structure and class?
CHAPTER 12
CONSTRUCTORS AND
DESTRUCTORS
Introduction: We know that, we cannot initialize the data members of the
class directly. We have learnt how to initialize the data members of the class
using member functions. In this chapter we will learn how to initialize the
data members automatically using a special member function called
constructor and how to delete the objects initialized by the constructor using
a function member called destructor to achieve memory optimization. In case
of constructors, we won’t call a constructor function explicitly.
Automatically, constructor functions will get invoked and executed. This
relieves the burden of calling the functions explicitly by the programmer.
Definition: A constructor is a special member function which is used to
initialize the data members of the class automatically.
Rules for writing a constructor function:
- A constructor always has the same name as that of the class name.
- There is no return type for constructors (not even void).
- A constructor should be declared in the public section.
- A constructor is invoked automatically when objects are created.
Constructors can have default arguments.
- It is not possible to refer to the address of the constructor.
- The constructors make implicit calls to the operators new and delete
when memory allocation is required.
- Constructors can be overloaded.
- A constructor cannot be declared as virtual.
- The const or volatile class objects cannot be initialized with a
constructor.
- The constructors are not inherited.
Example:
#include<iostream.h>
#include<conio.h>
class volume
{
int length, width, height;
public: volume() //Constructor
{
length=10;
width=15;
height=20;
}
void display()
{
cout<<"Volume="<<length*width*height;
}
};
void main()
{
volume v;
clrscr();
v.display();
getch();
}
Output:
Volume=3000
Observe that volume() is a special member function, that does not return any
type, not even void and name of the function is same as that of the class
name. It is a member function which is used to initialize the data members
length, width and height automatically. In the main() function we have not
called the volume() function explicitly. It is invoked automatically as soon as
the object of the class is created. The display() function is a user-defined
function used to show the volume as output.
Types of constructors: there are three types of constructors,
- Default constructor.
- Parameterized constructor.
- Copy constructor.
Default constructor: A constructor that does not receive any arguments is
called default constructor. As it receives no arguments, it is also called a zero
argument constructor.
Features of default constructor:
- Default constructor invokes automatically when an object of the class
is declared.
- All objects of a class are initialized to the same set of values by the
default constructor.
- If different objects are to be initialized with different values, it cannot
be done using the default constructor.
The program above depicts the use of default constructor. Let us take one
more programming example that illustrates the use of default constructor.
// Write a program to demonstrate the use of default constructor
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
public: student();
void display();
};
student::student()
{
rollno=1;
strcpy(name,"Hanumanth");
}
void student::display()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name="<<name<<endl;
}
void main()
{
student s;
clrscr();
s.display();
getch();
}
Output:
Roll number=1
Name=Hanumanth
Observe that, the constructor student() is defined outside the class definition
with scope resolution operator (::).
Disadvantages of default constructor:
- All objects of a class are initialized to the same set of values by the
default constructor.
- If different objects are to be initialized with different values, it cannot
be done using the default constructor.
Parameterized constructors: A constructor that takes one or more
arguments is called a parameterized constructor. With this constructor, it is
possible to initialize different objects with different values. These
constructors are also invoked automatically, whenever objects with
arguments are created. The parameters are used to initialize the object.
Features of parameterized constructors:
- The parameterized constructor can be overloaded.
- For an object created with one argument, constructor with only one
argument is invoked and executed.
- The parameterized constructor can have default arguments and default
values.
The constructor can be invoked in one of the following three ways.
- Explicit call
- Implicit call
- Initialization at the time of declaration with = operator
Explicit call: The declaration of an object is followed by assignment
operator; constructor name and argument list are enclosed in parenthesis.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
float percentage;
public: student(int rno, char nm[], float per)
{
rollno=rno;
strcpy(name,nm);
percentage=per;
}
void display()
{
cout<<"Student roll number: "<<rollno<<endl;
cout<<"Student name: "<<name<<endl;
cout<<"Student percentage: "<<percentage<<endl;
}
};
void main()
{
int r;
char n[20];
float p;
clrscr();
cout<<"Enter the roll number: ";
cin>>r;
cout<<"Enter the name: ";
cin>>n;
cout<<"Enter the percentage: ";
cin>>p;
student s=student(r,n,p); // Explicit call
s.display();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Sneha
Enter the percentage: 55
Student roll number: 1
Student name: Sneha
Student percentage: 55
Implicit call: The declaration of the object is followed by an argument list
enclosed in parentheses.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
float percentage;
public: student(int rno, char nm[], float per)
{
rollno=rno;
strcpy(name,nm);
percentage=per;
}
void display()
{
cout<<"Student roll number: "<<rollno<<endl;
cout<<"Student name: "<<name<<endl;
cout<<"Student percentage: "<<percentage<<endl;
}
};
void main()
{
int r;
char n[20];
float p;
clrscr();
cout<<"Enter the roll number: ";
cin>>r;
cout<<"Enter the name: ";
cin>>n;
cout<<"Enter the percentage: ";
cin>>p;
student s(r,n,p);
s.display();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Priyanka
Enter the percentage: 77
Student roll number: 1
Student name: Priyanka
Student percentage: 77
Initialization at the time of declaration with = operator: This way of
calling is used for the constructor with exactly one argument. In this method,
declaration is followed by assignment operator and value to be initialized.
#include<iostream.h>
#include<conio.h>
class data
{
int a;
public: data(int x)
{
a=x;
}
void display()
{
cout<<a;
}
};
void main()
{
data d=5;
clrscr();
cout<<"Value of a=";d.display();
getch();
}
Output:
Value of a=5
Copy constructor: It is a parameterized constructor used to copy one object
to another object of the same type.
Features of copy constructor:
- Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
/* Write a program to find the factorial of a number using a copy
constructor. */
#include<iostream.h>
#include<conio.h>
class fact
{
int n;
public: fact(int a);
int factorial();
};
fact::fact(int a)
{
n=a;
}
int fact::factorial()
{
int fact=1,i;
for(i=1;i<=n;i++)
fact=fact*i;
return fact;
}
void main()
{
int n1;
clrscr();
cout<<"Enter the number: ";
cin>>n1;
fact obj(n1);
fact copy=obj;
cout<<"Before copying: "<<n1<<"!="<<obj.factorial()<<endl;
cout<<"After copying: "<<n1<<"!="<<copy.factorial()<<endl;
getch();
}
Output:
Enter the number: 6
Before copying: 6!=720
After copying: 6!=720
Constructor overloading:
A class may contain more than one constructor. How we were overloading
functions, in a similar way constructor can also be overloaded.
/* Write a program to compute simple interest using overloaded
constructors. */
#include<iostream.h>
#include<conio.h>
class simple
{
float p,t,r,si;
public: simple()
{
}
simple(float a, float b, float c)
{
p=a;
t=b;
r=c;
}
void compute()
{
cout<<"Simple interest="<<p*t*r/100.0;
}
};
void main()
{
int pri, time, rate;
clrscr();
cout<<"Enter the principal amount: ";
cin>>pri;
cout<<"Enter the time: ";
cin>>time;
cout<<"Enter the rate of interest: ";
cin>>rate;
simple s(pri,time,rate);
s.compute();
getch();
}
Output:
Enter the principal amount: 1000
Enter the time: 5
Enter the rate of interest: 6
Simple interest=300
// Write a program to demonstrate the use of overloaded
constructors.
#include<iostream.h>
#include<conio.h>
class sample
{
int a,b;
public: sample()
{
a=10;
b=20;
}
sample(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"a="<<a<<" and b="<<b<<endl;
}
};
void main()
{
sample s1,s2(30,40);
clrscr();
cout<<"Sample 1: ";s1.display();
cout<<"Sample 2: ";s2.display();
getch();
}
Output:
Sample 1: a=10 and b=20
Sample 2: a=30 and b=40
Destructors: As we are familiar with the constructor, constructor is a special
member function which is used to initialize the data members of the class
automatically. In the same way, a destructor is a special function which is
used to deallocate memory location occupied by the object initialized by the
constructor. A destructor is a special member function that will be executed
automatically when an object is destroyed. The destructor name is the same
as that of the class and it is preceded by the tilde (~) symbol.
Rules for writing destructor are,
- The destructor name is the same as that of the class name, preceded by
the tilde (~) symbol.
- Destructors do not have a return value (not even void).
- Destructors take no arguments. Therefore, destructors cannot be
overloaded.
- The most common use of a destructor is to deallocate memory
allocated for the object by the constructor.
- Constructor should be declared in the public section.
The general form of defining destructor is,
class class_name
{
private: data_members;
public: class_name(); // Constructor
~class_name(); // Destructor
};
// Write a program to demonstrate the use of destructor
#include<iostream.h>
#include<conio.h>
class example
{
int a;
public: example()
{
a=10;
cout<<"Value of a in constructor: "<<a<<endl;
}
void display()
{
a=20;
cout<<"Value of a in display function: "<<a<<endl;
}
~example()
{
cout<<"Destructor invokes";
}
};
void main()
{
clrscr();
example e;
e.display();
getch();
}
Output:
Value of a in constructor: 10
Value of a in display function: 20
Destructor invokes
Note: The text “Destructor invokes” in destructor will not be printed if you
execute the program. Trace this program by pressing F7 (in Turbo C++
Compiler) to reach control flow to the destructor. Before the compiler prints
the text present in the destructor, the object created and initialized by the
constructor will be destroyed. Hence, it is not going to show the text present
in the destructor.
If multiple objects are created, these objects are destroyed in the reverse order
of their creation. For example, the declaration statement
example e1, e2, e3;
object e1 creates first, next e2 and then e3. These objects destroy e3 first, e2
next and e1 last.
/* Write a program to demonstrate that the objects will destroy in
reverse order of their creation in destructor. */
#include<iostream.h>
#include<conio.h>
int count=0;
class example
{
public: example()
{
count++;
cout<<"In the constructor, object "<<count<<" is created."<<endl;
}
~example()
{
cout<<"In destructor, object "<<count<<" is destroyed."<<endl;
count--;
}
};
void main()
{
clrscr();
example e1,e2,e3;
getch();
}
Output:
In the constructor, object 1 is created.
In the constructor, object 2 is created.
In the constructor, object 3 is created.
In destructor, object 3 is destroyed.
In destructor, object 2 is destroyed.
In destructor, object 1 is destroyed.
EXERCISES
1. What is a constructor? Explain the rules for writing constructor.
2. Write a program to demonstrate the use of constructor.
3. What are the types of constructors?
4. Explain the default constructor with an example.
5. Describe the parameterized constructor with an example.
6. Explain the copy constructor with a programming example.
7. Explain constructor overloading with an example.
8. What is a destructor? Explain with a programming example.
CHAPTER 13
OPERATOR OVERLOADING
Introduction: The operator used in one instance for a specific purpose may
not be used by the same operator for the same purpose in another instance.
Meaning that, an operator performs differently at different instances of time.
It does not change its syntax but it changes its semantics. Let us consider
examples such as, the operator ‘+’ is used with the numbers and acts as an
arithmetic operator, when the same operator is used with the string then it
acts as a concatenation operator. Similarly, >> and << operators are used as
input and output operators with cin and cout objects respectively. These same
operators act differently when used with bitwise operations, they act as a
bitwise right shift operator and bitwise left shift operator. When we consider
an * (asterisk) operator, when used with two or more operands acts as an
arithmetic product whereas, when used as unary operator, acts as a pointer. In
this chapter we will learn how different operators behave differently. This
process of using operators differently at different instances of time is called
operator overloading.
The general form to define operator overloading is,
return_type class_name::operator opr(argument_list)
{
// function body
}
Here, operator is a keyword used before the built-in operator and the rest of
the syntax is similar to the function definition.
Example 1:
void string::operator + (string s1, string s2)
{
// string concatenation
}
void product::operator * (product e1, product e2)
{
// multiplication of two objects
}
Overloadable operators: Following table shows a list of operators that can
be overloaded.
Assignment Arithmetic Relational Logical Bitwise Increment Special
operator operator operator operator operator and operator
decrement
operator
= + < ! & ++ ,
- <= && | -- []
* > || ~ ()
/ >= ^ ->
% == << ->*
+= != >> new
-= <<= new[]
*= >>= delete
/= &= delete[]
%= |=
^=
EXERCISE
1. What is operator overloading? Write its syntax and example.
2. List overloadable and non-overloadable operators.
3. Write a program to illustrate the use of the overloading minus (-)
operator.
4. Write a program to illustrate the use of overloading plus (+)
operator.
5. Write a program to illustrate the use of an overloading operator =.
6. Write a program to illustrate the use of overloading [ ] operator.
7. Write a program to illustrate the use of overloading () operator.
8. Write a program to illustrate the use of overloading -> operator.
9. Write a program to illustrate the use of overloading ++ and --
operator.
10. Write a program to illustrate the use of overloading new and delete
operators.
CHAPTER 14
CLASS TEMPLATES
Introduction: class template is a generic type that can be reused for different
data types. C++ allows function template and class template. In chapter 8 we
have already studied function templates. Now in this chapter we’ll learn class
templates.
Class template definition: A single generic container class that is capable of
handling different data types.
The general form of a class template is,
template <class template_parameter>
class class_name
{
Class body;
};
Example:
template <class T>
class example
{
T a,b;
public: void getdata();
void putdata();
};
Here, template parameter T is replaced by built-in or user-defined data types
when the class template is instantiated. If the template instantiated to int then
the private members a and b will become int type. if the template is
instantiated to float then the private members a and b will become float type.
/* Write a program to find the sum of two numbers using a class
template. */
#include<iostream.h>
#include<conio.h>
template <class T>
class sum
{
T a,b,sum;
public: void getdata();
void add();
};
template <class T>
void sum <T> ::getdata()
{
cout<<"Enter two numbers:\n";
cin>>a>>b;
}
template <class T>
void sum <T> :: add()
{
T sum;
sum=a+b;
cout<<a<<"+"<<b<<"="<<sum<<endl;
}
void main()
{
clrscr();
sum <int> intobj;
sum <float> floatobj;
cout<<"Integer sum\n";
intobj.getdata();
intobj.add();
cout<<"Floating-point sum\n";
floatobj.getdata();
floatobj.add();
getch();
}
Output:
Integer sum
Enter two numbers:
4
6
4+6=10
Floating-point sum
Enter two numbers:
3.2
5.5
3.2+5.5=8.7
Class template instantiation: the process of substituting the template
parameter with the various built-in and user-defined data types is known as
template instantiation. If this instantiation is able to generate a class from the
generic class template definition then it is called the class template
instantiation.
// Write a program
#include<iostream.h>
#include<conio.h>
template <class T>
class array
{
T *ptr;
int size;
public: array(T a[], int s);
void display();
};
template<class T>
array<T>::array(T a[],int s)
{
ptr=new T[s];
size=s;
for(int i=0;i<size;i++)
ptr[i]=a[i];
}
template<class T>
void array<T>::display()
{
for(int i=0;i<size;i++)
cout<<" "<<*(ptr+i);
cout<<endl;
}
void main()
{
clrscr();
int a[5]={2,4,6,8,10};
array<int> b(a,5);
b.display();
getch();
}
Output:
2 4 6 8 10
Member functions of a class definition: A member function can be defined
inside or outside the class definition. This concept is already learnt. If you
want to define a function outside the class definition then there is a special
member syntax as shown below. (This is already covered in the above
programming examples).
template <class T>
void sum<T> :: getdata()
{
cout<<”Enter two numbers:\n”;
cin>>a>>b;
}
/* Write a program to find the biggest of numbers and characters by
defining member functions outside the class definition. */
#include<iostream.h>
#include<conio.h>
template <class T>
class biggest
{
T a,b;
public: T max(T a, T b);
void getdata();
void display();
};
template <class T>
void biggest<T>::getdata()
{
cout<<"Enter two numbers or characters:\n";
cin>>a>>b;
}
template <class T>
T biggest<T>::max(T a, T b)
{
return(a>b)?a:b;
}
template<class T>
void biggest<T>::display()
{
cout<<"Biggest="<<max(a,b)<<endl;
}
void main()
{
clrscr();
biggest <int> intobj;
biggest <float> floatobj;
biggest <char> charobj;
cout<<"Biggest in Integer numbers:\n";
intobj.getdata();
intobj.display();
cout<<"Biggest in floating-point numbers:\n";
floatobj.getdata();
floatobj.display();
cout<<"Biggest in character:\n";
charobj.getdata();
charobj.display();
getch();
}
Output:
Biggest in Integer numbers:
Enter two numbers or characters:
4
6
Biggest=6
Biggest in floating-point numbers:
Enter two numbers or characters:
2.3
5.6
Biggest=5.6
Biggest in character:
Enter two numbers or characters:
d
f
Biggest=f
Friend declarations in class templates:
We know that the friend function is used to access private members of the
class. The same is implemented in the class template. There are three ways of
declaring friends.
- A non-template friend class or friend function.
- A bound friend class template or function template.
- An unbound friend class template or function template.
Let us take an example of a non-template friend or friend function.
class sum
{
private: void calculate();
};
template <class T>
class add
{
friend class combine;
friend void sum::calculate();
};
Here, the class combine should not be defined or declared in the global scope
before it is declared as friend in the class template add.
If we consider the second method of declaring the friend function in a class
template, there is one-to-one correspondence between the class template
sum’s instantiation and its friend.
template <class T>
class sum
{
private: void calculate();
}
template<class T>
class combine
{
// class definition
};
template <class T>
class add
{
friend class combine<T>;
friend void sum<T>::calculate();
};
Observe that the declaration or definition is made for the template before it is
used for declaring a friend within a class template.
In an unbound friend class template or function template method of declaring
the friend functions, there is also a one-to-one correspondence between the
class template sum’s instantiation and its friend. Observe the following
declaration.
template<class T>
class add
{
template<class T>
friend void sum<T>::calculate();
};
Nested class templates:
Similar to nested classes, class templates can also be enclosed one within
another. A nested class can be placed in either a private or public section of
an enclosing class template. When it is placed in the private section, it is not
accessible to the program. However it is accessible by enclosing the class
template and its friend.
Example:
template<class T>
class list
{
private: class node
{
T data;
node *ptr;
};
node *head, *temp;
public: //public members
};
Where class node is the nested class template while class list is the enclosing
class template. When a class list is instantiated, it generates its own node
class with the correct template argument for T. There is one-to-one
correspondence between the instantiation of the nested class template and its
enclosing class template.
Member templates: It is possible to write a function template or class
template as a member of normal class or member of a class template. Let us
take an example.
template<class T>
class example
{
private: // class member template
template <class U>
class integer_number
{
U data;
T value;
};
public: // function member template
template <class Type>
void sum(Type a, Type b)
{
Type c=a+b;
cout<<”c=”<<c;
}
};
Observe that, one private class member template and one public function
member template. Class member template integer_number has U and the
function member template sum has Type as template parameter. The
enclosing template integer_number has T as its template parameter. This can
be used inside the nested templates. Thus, the declaration
T value;
In the class member template integer_number.
EXERCISES
1. Define class template with its syntax and an example.
2. Write a program to find the sum of two numbers using a class
template.
3. What is class instantiation? Explain with a programming example.
4. Explain member functions of a class template with an example.
5. Describe how to declare a friend in class template declaration.
6. Briefly explain the nested class templates with an example.
7. Explain how to write member templates with an example.
CHAPTER 15
INHERITANCE
Introduction:
C++ classes can be used in several ways. This is done by creating new
classes, reusing the properties of existing one. It allows the user to create a
new class (derived class) from an existing class (base class). The derived
class inherits all the features from a base class and it can have additional
features of its own.
Definition: “Inheritance is the capability of one class to inherit properties
from another class”.
Inheritance is a process of acquiring properties from one class to another.
Base class: A class whose properties are inherited to another class is called
base class.
Derived class: A class whose properties are inherited from another class is
called derived class.
Advantages of Inheritance:
- Inheritance permit to reuse already existing code.
- Reduces development time.
- Easy to maintain.
- Easy to extend.
- Memory can be utilized properly.
If we do not use inheritance, then there are two disadvantages,
- Code written in the base class is to be repeated in the derived class that
leads to wastage of memory space.
- Testing to be done separately for both base and derived class that takes
a lot of time.
These problems can be solved using inheritance. If we reuse already existing
code in the base class then the above problems can be tackled.
In the below example, you can find a base class called Employee which
inherits properties to two other derived classes called supervisor and
manager that receives properties from the base class. These classes have
properties of base class in addition they have their own properties.
Defining the derived class: The syntax for defining the derived class is as
shown below.
class derived_class:visibility_mode base_class
{
// class body
};
Where, class is a keyword. derived_class is a valid identifier name of the
derived class and colon (:) shows the derivation from the base class.
visibility_mode specifies the type of derivation (private, public or protected).
base_class is a valid identifier name of base class.
The class body consists of properties of a base class and its own properties.
The base class must be terminated by a semicolon.
Visibility mode: The visibility mode (private, public and protected) in the
definition of derived class specifies whether the features of the base class are
privately derived or publicly derived or protected derived.
The following table shows the role of visibility mode,
Derived class
Base class
Public mode Private mode Protected mode
Private Not inherited Not inherited Not inherited
Public Public Private Protected
Protected Protected Private Protected
Private inheritance:
- The public members of the base class become the private members of
the derived class. They can be accessed by the member functions of the
derived class.
- The private members of the base class are not inherited by the derived
class.
- The protected members of the base class become private members to
the derived class.
/* Write a program to demonstrate the single inheritance in private
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:private father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata(); //accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display(); //accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Public inheritance:
- The public members of the base class become public to the derived
class.
- The private members of the base class cannot be inherited to the
derived class.
- The protected members of the base class stay protected in the derived
class.
/* Write a program to demonstrate the single inheritance in public
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:public father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata(); //accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display(); //accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Protected inheritance:
- The public members of the base class become protected in the derived
class.
- The protected members of the base class stay protected in the derived
class.
- The private members of the base class cannot be inherited to the
derived class.
/* Write a program to demonstrate the single inheritance in protected
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:protected father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata();
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display();
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Multilevel inheritance: The classes can also be derived from the classes
that are already derived is called multilevel inheritance.
Multiple inheritance: If a class is derived from more than one base class
is known as multiple inheritance.
******Information of manager******
Employee id=1
Employee name=Hanumanth
Designation=Manager
Salary=100000
******Information of supervisor******
Employee id=2
Employee name=Swaroop
Designation=Supervisor
Salary=50000
******Information of clerk******
Employee id=3
Employee name=Raj
Designation=Clerk
Salary=25000
Hybrid inheritance: Hybrid inheritance is a combination of hierarchical
and multiple inheritance.
/* Write a program to illustrate hybrid inheritance using multilevel-
multiple inheritance. */
#include<iostream.h>
#include<conio.h>
class grandfather
{
char name[20];
int age;
public: char complexion[10];
void getdata();
void putdata();
};
class father:public grandfather
{
char qualification[20];
float salary;
public: char complexion[10];
char gender;
void inputdata();
void outputdata();
};
class mother
{
char hobby[20];
public: void getting();
void putting();
};
class son:public father, public mother
{
char designation[20];
public: void readdata();
void writedata();
};
void grandfather::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
}
void grandfather::putdata()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
}
void father::inputdata()
{
grandfather::getdata(); // accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void father::outputdata()
{
grandfather::putdata(); // accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void mother::getting()
{
cout<<"Enter the hobby: ";
cin>>hobby;
}
void mother::putting()
{
cout<<"Hobby="<<hobby<<endl;
}
void son::readdata()
{
father::inputdata();
mother::getting();
cout<<"Enter the designation: ";
cin>>designation;
}
void son::writedata()
{
father::outputdata();
mother::putting();
cout<<"Designation="<<designation<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the qualification: MSc
Enter the salary: 100000
Enter the hobby: Cooking
Enter the designation: Lecturer
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
Qualification=MSc
Salary=100000
Hobby=Cooking
Designation=Lecturer
One more program can be written using hierarchical-multiple inheritance.
This is left to you to write the program on the same.
Virtual base classes: A situation where the program design would require
one base class call it A and two derived classes namely B and C, which are
inherited from the base class A. Furthermore, derived class D is created
from B and C. See the figure given below.
In the public inheritance, B and C inherit one copy of the base class data,
whereas derived class D inherited from B and C get two copies of the base
class data.
Suppose, a member function of D wants to access the data members of the
base class an ambiguity problem of which two copies is to access will be
encountered. The compiler will generate an error message for this
ambiguity. To overcome this problem, the derived class B and C should be
declared as virtual.
// Write a program to illustrate virtual base class
#include<iostream.h>
#include<conio.h>
class A
{
protected: int a;
public: void geta();
void puta();
};
class B:virtual public A
{
protected: int b;
public: void getb();
void putb();
};
class C: virtual public A
{
protected: int c;
public: void getc();
void putc();
};
class D:public B, public C
{
int sum;
public: void display();
};
void A::geta()
{
cout<<"Enter the value of a: ";
cin>>a;
}
void A::puta()
{
cout<<"a="<<a<<endl;
}
void B::getb()
{
cout<<"Enter the value of b: ";
cin>>b;
}
void B::putb()
{
cout<<"b="<<b<<endl;
}
void C::getc()
{
cout<<"Enter the value of c: ";
cin>>c;
}
void C::putc()
{
cout<<"c="<<c<<endl;
}
void D::display()
{
sum=a+b+c;
puta();
putb();
putc();
cout<<"\nSum="<<sum<<endl;
}
void main()
{
D d;
clrscr();
d.geta();
d.getb();
d.getc();
d.display();
getch();
}
Output:
Enter the value of a: 1
Enter the value of b: 2
Enter the value of c: 3
a=1
b=2
c=3
Sum=6
Abstract classes: It is a class that is not used to create objects. An abstract
class is defined only to act as a base class.
Constructors and destructors in derived classes:
When both the base and derived classes contain constructors, the base
class constructor is executed first and then the constructor in the derived
class is executed.
If the constructors are called down the line from the base to the derived
class, the destructors are called just in the reverse order. That is from the
derived class up to the base class.
/* Write a program to illustrate constructor and destructors in
derived classes. */
#include<iostream.h>
#include<conio.h>
class A
{
public: A()
{
cout<<"In base class constructor"<<endl;
}
~A()
{
cout<<"In base class destructor"<<endl;
}
};
class B:public A
{
public: B()
{
cout<<"In derived class constructor"<<endl;
}
~B()
{
cout<<"In derived class destructor"<<endl;
}
};
void main()
{
clrscr();
B obj;
getch();
}
Output:
In base class constructor
In derived class constructor
In derived class destructor
In base class destructor
Note: Trace this program to get the output as shown above. Otherwise,
only the first two statements will be displayed and the other two will not.
This is because before the statements are printed the destructor invokes.
Trace this program by pressing the F7 button (in Turbo C++ compiler) to
get the output as shown above.
EXERCISES
1. What is inheritance? Mention the access specifiers used in C++.
2. Explain single inheritance with a programming example.
3. Explain multilevel inheritance with a programming example.
4. Explain multiple inheritance with a programming example.
5. Explain hierarchical inheritance with a programming example.
6. Explain hybrid inheritance with a programming example.
7. What is a virtual base class? Explain with a programming example.
8. How do constructors and destructors invoke base and derived
classes? explain with a programming example.
CHAPTER 16
POLYMORPHISM AND VIRTUAL
FUNCTIONS
Introduction: In the previous lessons we have studied about some of the
features of OOP such as, data encapsulation, inheritance, polymorphism etc.
we are familiar with all of the features of OOPs but in this chapter, we will
learn still more about polymorphism.
Polymorphism can be achieved in two ways, one at the compile time and
another is at run-time. We have studied, implementation of compile time
polymorphism using function overloading and operator overloading. And the
run-time polymorphism is achieved using the virtual functions.
student_friend sf;
clrscr();
sp->read();
sp->display();
sp=&sf;
sp->read();
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Swaroop
enter the fees: 15000
register number=1
student name=Swaroop
student fees=15000
enter the register number: 2
enter the student name: Raj
enter the fees: 12000
register number=2
student name=Raj
student fees=12000
Observe that, this program always shows the contents of the base class object
only. To display the contents of the derived class object, it is necessary to
type cast the pointer as shown in the following program.
/* Write a program to illustrate the type casting a pointer to objects in
single inheritance. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees<<endl;
}
class student_friend:public student//single inheritance
{
int age;
char hobby[20];
public: void read();
void display();
};
void student_friend::read()
{
student::read();
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the hobby: ";
cin>>hobby;
}
void student_friend::display()
{
student::display();
cout<<"Age="<<age<<endl;
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
student s,*sp;
sp=&s;
student_friend sf;
clrscr();
sp->read();
sp->display();
sp=&sf;
((student_friend *)sp)->read(); // pointer typecasting
((student_friend *)sp)->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Swaroop
enter the fees: 15000
register number=1
student name=Swaroop
student fees=15000
enter the register number: 2
enter the student name: Raj
enter the fees: 12000
Enter the age: 15
Enter the hobby: Walking
register number=2
student name=Raj
student fees=12000
Age=15
Hobby=Walking
Virtual functions: In the above program we have seen that the pointer to
object calls members of the base class. Addressing the appropriate object can
be done in two ways.
- Type Casting pointers
- Virtual functions.
We have come across type casting pointers, now we will learn about virtual
functions. The virtual function is used to achieve run-time polymorphism. A
member function of a class can be made virtual. The process of redefining a
virtual function in the derived classes is called function overriding.
Rules for writing virtual functions:
- The virtual functions must be defined in a base class.
- The virtual functions cannot be static members.
- The virtual functions can be declared as the friend functions to some
other class.
- The virtual functions should be declared in the public section of a
class.
- The prototype of the virtual functions must be the same in both base
and derived classes.
- A base class pointer can be used to address the derived class object.
But vice-versa is not true.
- No constructor is made as virtual, but the destructor can be made as
virtual.
Advantages of virtual functions:
- Virtual functions eliminate the necessity of typecasting the pointer to
access the member functions of the derived class object.
- The virtual function increases run-time efficiency.
/* Write a program to demonstrate virtual functions and the object to
pointer in achieving the run-time polymorphism. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: virtual void read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
virtual void display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees<<endl;
}
};
class student_friend:public student//single inheritance
{
int age;
char hobby[20];
public: void read();
void display();
};
void student_friend::read()
{
student::read();
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the hobby: ";
cin>>hobby;
}
void student_friend::display()
{
student::display();
cout<<"Age="<<age<<endl;
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
student s,*sp;
sp=&s;
student_friend sf;
clrscr();
sp->read();
sp->display();
sp=&sf;
sp->read(); // pointer typecasting
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Priyanka
enter the fees: 10000
register number=1
student name=Priyanka
student fees=10000
enter the register number: 2
enter the student name: Sneha
enter the fees: 8000
Enter the age: 21
Enter the hobby: music
register number=2
student name=Sneha
student fees=8000
Age=21
Hobby=music
Pure virtual functions:
A virtual function which provides an interface for the derived class functions
to override but must not itself be invoked through the virtual mechanism is
called a pure virtual function.
Rules for writing pure virtual functions:
- A pure virtual function is a “do-nothing” member function.
- A pure virtual function can only be declared in the base class, not the
definition.
- A class having pure virtual functions cannot be used to instantiate
objects of its own.
The general form of declaring a pure virtual function,
virtual return_type function_name()=0;
// Write a program to illustrate a pure virtual function
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public: virtual void read()
{
cout<<"Enter the value of a: ";
cin>>a;
}
virtual void display()=0; // pure virtual function
};
class derived:public base
{
int b;
public: void read()
{
cout<<"Enter the value of b: ";
cin>>b;
}
void display()
{
cout<<"In derived class b="<<b<<endl;
}
};
void main()
{
clrscr();
base *bptr;
derived d;
bptr=&d;
bptr->read();
bptr->display();
getch();
}
Output:
Enter the value of b: 10
In derived class b=10
Virtual destructors:
We use virtual destructors when the objects in the derived class are created
dynamically using the new operator. the address of the derived class object
can be assigned to the pointer which points to the base class object. When we
want to delete the base pointer, it calls the base class destructor. In reality, the
derived class destructor must be called first and then the base class destructor.
To achieve this, we have to declare a virtual destructor in the base class.
// Write a program to illustrate the virtual destructor
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public: base()
{
cout<<"Enter the value of a: ";
cin>>a;
}
virtual ~base()
{
cout<<"In the base class destructor a="<<a<<endl;
}
};
class derived:public base
{
int b;
public: derived()
{
cout<<"Enter the value of b: ";
cin>>b;
}
~derived()
{
cout<<"In the derived class destructor b="<<b<<endl;
}
};
void main()
{
clrscr();
base *bptr=new derived;
delete bptr;
getch();
}
Output:
Enter the value of a: 5
Enter the value of b: 10
In the derived class destructor b=10
In the base class destructor a=5
EXERCISES
1. What is run-time polymorphism? Classify polymorphism.
2. Describe pointers to objects with a programming example.
3. Write a program to demonstrate the pointer to derived classes.
4. How to do pointer typecasting? Explain with a programming
example.
5. What are virtual functions? Explain with an example.
6. State the rules for virtual functions.
7. Write the advantages of virtual functions.
8. What are pure virtual functions? Explain with an example.
9. How virtual destructors are used? Explain with suitable examples.
CHAPTER 17
FILE HANDLING
Introduction: We are familiar with cin and cout objects belonging to the
iostream class which are used to perform input and output operations. These
objects are used to accept input through the keyboard and display output on
to the monitor.
In C++, the input and output operations are sequences of flow of character
(bytes). An input and output stream are a flow of bytes from a device like a
keyboard, a disk drive or network connection etc. to main memory, called
input operation. If the bytes flow from main memory to a device like a
monitor, a printer, a disk drive or a network connection etc, is called output
operation.
Almost all computers utilize files, because files are used to store the
information permanently. Files are the basic storage for data. Word
processors create document files. Database programs create files of
information. Compilers and interpreters convert source programs into object
code files and executable files. A file itself is a bunch of bytes stored on
storage devices such as, magnetic tape, magnetic disk etc.
In C++, file input output operations can be performed using the header file
fstream.h. File input operations can be performed using istream.h and file
output operations can be performed using ostream.h.
The stream that supplies data to the program is known as input stream. It
reads the data from the file and hands it over to the program. The stream that
receives the data from the program is known as output stream. It writes the
received data to the file. These input output operations are depicted in the
following figure.
Stream class hierarchy for I/O operations:
All I/O operations can be performed by the stream classes that are derived
from two common base classes called ios and streambuf. The class ios is a
base class for the classes istream (an input stream), ostream (an output
stream) and iostream (an input-output stream). The following figure depicts
the stream class hierarchy for input output operations.
The three derived classes of ios, istream, ostream and fstream are used to
create an input stream, output stream and input-output stream.
Type of data files: We know that the files are used to store the data or
information permanently for future reference.
The data files are classified based on how data are stored and retrieved as,
- Text file
- Binary file
Text file:
- The information stored is in the form of Bits.
- No delimiters are used for a line.
- No translation required.
Binary file:
- The information stored is in the form of ASCII characters.
- Each line of text is terminated with a special character known as EOL
(End Of Line) character.
- Internal translation occurs.
Opening and closing files:
To create an input stream, you must declare the stream to be of class ifstream.
To create an output stream, you must declare the stream to be of class
ofstream. Streams that will be performing both input and output operations
must be declared as class fstream.
Opening a file can be accomplished in two ways:
- Opening file using constructor.
- Opening file using open() member function
Opening a file using constructor:
Syntax of opening a file for output only,
ofstream ofstream_object(“File_name”);
Example: ofstream fout(“text.dat”);
Where, fout is declared to be an object of ofstream type and it opens the
file text.dat in output purpose only.
Syntax of opening a file for input only,
ifstream ifstream_object(“file_name”);
Example: ifstream fin(“text.dat”);
Where, fin is declared to be an object of ifstream type and it opens the file
text.dat in input purpose only.
Opening a file using open():
Syntax of opening a file for output only,
ofstream_object.open(“file_name”) ;
Example: ofstream ofile;
ofile.open(“text.dat”);
Syntax of opening a file for input only,
ifstream_object.open(“file_name”);
Example: ifstream ifile;
ifile.open(“text.dat”);
if we have to open a file for both input and output operations, we use objects
of fstream class.
the syntax for opening a file an object of fstream class and the constructor is
as follows:
fstream fstream_object(“filename”,mode)
the syntax for opening a file an object of type fstream class and the open()
member function is as follows:
fstream_object.open(“filename”,mode)
The following table describes the type of file modes.
Mode Explanation
ios :: in Open a file for reading.
ios :: out Open a file for writing.
ios :: app Appends data to the end of the file.
File pointer moves to the end of the file but allows
ios :: ate writing data in any location in the file.
run 1:
Enter the size of an array: 5
Enter the elements
1
1
1
2
3
Enter the element whose frequency is to be checked: 1
1 has appeared 3 times
run 2:
Enter the size of an array: 5
Enter the elements
1
2
3
4
5
Enter the element whose frequency is to be checked: 6
6 has appeared 0 times
#include<iostream.h>
#include<conio.h>
#include<math.h>
class quad
{
float x1,x2,imaginarypart,realpart,discriminant,a,b,c;
public: void getdata()
{
cout<<"Enter the values of a, b, c: ";
cin>>a>>b>>c;
discriminant=b*b-4*a*c;
}
void putdata()
{
if(discriminant>0)
{
x1=(-b+sqrt(discriminant))/(2*a);
x2=(-b-sqrt(discriminant))/(2*a);
cout<<"Roots are real and different:\n";
cout<<"x1="<<x1<<" and x2="<<x2;
}
else if(discriminant==0)
{
x1=-b/(2*a);
cout<<"Roots are real and equal\n";
cout<<"x1=x2="<<x1;
}
else
{
realpart=-b/(2*a);
imaginarypart=sqrt(-discriminant)/(2*a);
cout<<"Roots are imaginary\n";
cout<<realpart<<"+"<<imaginarypart<<"i"<<endl;
cout<<realpart<<"-"<<imaginarypart<<"i";
}
}
};
void main()
{
quad q;
clrscr();
q.getdata();
q.putdata();
getch();
}
Output:
run 1:
Enter the values of a, b, c: 1
2
2
Roots are imaginary
-1+1i
-1-1i
run 2:
Enter the values of a, b, c: 1
4
4
Roots are real and equal
x1=x2=-2
run 3:
Enter the values of a, b, c: 1
5
6
Roots are real and different:
x1=-2 and x2=-3
/* 4. Program to find the area of a square/rectangle/triangle using
function overloading. */
#include<iostream.h>
#include<conio.h>
class function_overloading
{
public: int area(int a) // area of a square
{
return(a*a);
}
int area(int l,int w) // area of a rectangle
{
return(l*w);
}
double area(double b,double h)
{
return(0.5*b*h);
}
};
void main()
{
function_overloading f;
clrscr();
cout<<"Area of square="<<f.area(5)<<endl;
cout<<"Area of rectangle="<<f.area(5,10)<<endl;
cout<<"Area of triangle="<<f.area(2.0,3.0);
getch();
}
Output:
Area of square=25
Area of rectangle=50
Area of triangle=3
// 5. Program to find the cube of a number using inline functions.
#include<iostream.h>
#include<conio.h>
inline int cube(int a)
{
return(a*a*a);
}
void main()
{
int x,y;
clrscr();
x=cube(5);
cout<<"Cube of 5="<<x<<endl;
y=cube(10);
cout<<"Cube of 10="<<y;
getch();
}
Output:
Cube of 5=125
Cube of 10=1000
/* 6. Write a program to find the sum of the series 1+x+x^2+...+x^n
using constructors. */
#include<iostream.h>
#include<conio.h>
class series
{
int x,n;
public: series(int x1,int n1)
{
x=x1;
n=n1;
}
void display();
};
void series::display()
{
int sum=1;
for(int i=0;i<n;i++)
{
sum=sum*x;
sum=sum+1;
}
cout<<"Sum of the series 1+x+x^2+...+x^n="<<sum;
}
void main()
{
int x1,n1;
clrscr();
cout<<"Enter the value of x: ";
cin>>x1;
cout<<"Enter the value of n: ";
cin>>n1;
series s(x1,n1);
s.display();
getch();
}
Output:
Enter the value of x: 2
Enter the value of n: 3
Sum of the series
1+x+x^2+...+x^n=15
/* 7. Create a base class containing the data members roll number and
name. Also create a member function to read and display the data using
the concept of single level inheritance. Create a derived class that
contains marks of two subjects and total marks as the data members. */
#include<iostream.h>
#include<conio.h>
class abc
{
int rollno;
char name[20];
public:
void read()
{
cout<<"enter roll no and name"<<endl;
cin>>rollno>>name;
}
void display()
{
cout<<"roll no:"<<rollno<<endl;
cout<<"name:"<<name<<endl;
}
};
class xyz:public abc
{
int m1;
int m2;
int t;
public:
void read1()
{
cout<<"enter the first marks & second marks:";
cin>>m1>>m2;
t=m1+m2;
}
void display1()
{
cout<<"first marks="<<m1<<endl;
cout<<"second marks="<<m2<<endl;
cout<<"total marks="<<t<<endl;
}
};
void main()
{
xyz ob;
clrscr();
ob.read();
ob.read1();
ob.display();
ob.display1();
getch();
}
Output:
enter roll no and name
1
Sonia
enter the first marks & second marks:67
77
roll no:1
name:Sonia
first marks=67
second marks=77
total marks=144
/* 8. Create a class containing the following data members register No.,
name and fees. Also create a member function to read and display the
data using the concept of pointers to objects. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees;
}
void main()
{
student s,*sp;
sp=&s;
clrscr();
sp->read();
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Rakshita
enter the fees: 1000
register number=1
student name=Rakshita
student fees=1000
// 9. Write a program to demonstrate hierarchical inheritance.
#include<iostream.h>
#include<conio.h>
class book
{
protected: char book_title[20];
char author_name[20];
float price;
public: void getdata();
void putdata();
};
class textbook:public book
{
protected: int pages;
int stock;
public: void getdata();
void putdata();
};
class comicbook:public book
{
protected: int pages;
int stock;
public: void getdata();
void putdata();
};
void book::getdata()
{
cout<<"Enter the book title: " ;
cin>>book_title;
cout<<"Enter the name of the author: ";
cin>>author_name;
cout<<"Enter the price of the book: ";
cin>>price;
}
void book::putdata()
{
cout<<"Book title: "<<book_title<<endl;
cout<<"Author name: "<<author_name<<endl;
cout<<"Price :"<<price<<endl;
}
void textbook::getdata()
{
book::getdata();
cout<<"Enter the number of pages: ";
cin>>pages;
cout<<"Enter the stock: ";
cin>>stock;
}
void textbook::putdata()
{
book::putdata();
cout<<"Number of pages: "<<pages<<endl;
cout<<"Number of books in stock: "<<stock<<endl;
}
void comicbook::getdata()
{
book::getdata();
cout<<"Enter the number of pages: ";
cin>>pages;
cout<<"Enter the stock: ";
cin>>stock;
}
void comicbook::putdata()
{
book::putdata();
cout<<"Number of pages: "<<pages<<endl;
cout<<"Number of books in stock: "<<stock<<endl;
}
void main()
{
textbook tb;
comicbook cb;
clrscr();
cout<<"Details of text book:\n";
tb.getdata();
cout<<"Details of comic book:\n";
cb.getdata();
cout<<"\n***** Information of text book *****\n";
tb.putdata();
cout<<"\n***** Information of comic book *****\n";
cb.putdata();
getch();
}
Output:
Enter the name of the author: Hanumanth
Enter the price of the book: 600
Enter the number of pages: 330
Enter the stock: 1000
Details of comic book:
Enter the book title: Chanakya
Enter the name of the author: Priyanka
Enter the price of the book: 230
Enter the number of pages: 230
Enter the stock: 500
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
s[i][j]=a[i][j]+b[i][j];