You are on page 1of 272

www.alljntuworld.

in JNTU World

NT
J Object Oriented Provided

U
C++ Programming by JNTU
W
World Team

or
through C++
ld
1 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
SYLLABUS
Module Introduction and values Module Abstraction functions, Inheritance: inheritance,
derived Polymorphism: Ambiguity binding, Operator member Exception declaration, release.
Module Dynamic assignment Template: Standard types. Namespaces: Object

J encapsulation. in Oriented class method operator I functions, II III Overloading:


N
(08 memory inline Template (16 in template handling: (16 operator, role

to mechanism: constructors. unexpected Class function user hrs) hrs)


hrs) object function, Binding, Design, overriding of function, defined recursion, Getting
management, virtual classes, hierarchy, Library: virtual Try, oriented overloading, This

T
design Static friend exceptions, Classes, namespaces, base operator with
throw, started destructor. pointer, template namespaces, Fundamental binding, and functions,

U
programming, virtual class, derived private, new programming,

and with overloading, dynamic applications functions. exception constructor functions, Dynamic
namespaces catch, and C++ classes, static operators, public, idea syntax, delete
polymorphism: user members, exceptions I/O about binding, pure when of role and

W
constructors, single defined this operators. provided flow operators,
data-type, virtual of destructor string, handling pointer, classes. Static control, and inheritance,
and types, functions, by Base references. iterators, polymorphism: derived library. destructors,
Operator variables, object arrays exceptions, execution, structures, class

o
abstract multiple, hashes, and copying, classes, pointer, function, strings,

pointers. member base unions, resource Function classes. iostreams function object

r
multilevel, initialization copy functions, member polymorphism, data, Overloading,
ld
capture constructor, slicing,

and exception member and default hybrid


other using
non late
and
Provided by JNTU World Team (www.alljntuworld.in)
2
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
CONTENTS Chapter No Chapter 1 Chapter 2 Chapter 3 Chapter 4
Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10
NT
J Chapter Introduction Class

Inheritance Polymorphism Operator Exception Dynamic Templates

U
Standard Namespace Previous and Name Year

Memory Overloading Template Object Handling BPUT


W
Management Library Questions

or ld
Page No

1
30
48
64
73
82
92
99
107
112
120
3 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Chapter 1
Procedure/ structure oriented Programming
• Conventional programming, using commonly known as procedure-oriented • In the
procedure-oriented approach, such as reading, calculating and printing. tasks.
• The primary focus is on functions.
Global Data Function-1 Local Data

Object J • • • • • Object Data Functions Emphasis Programs Data Objects


N
New Oriented data A is hidden may and is are Programming on

T
communicate divided functions and data cannot rather into can Object Data
U
Functions what be than with be accessed easily are procedure.

each C known high Function-2 the Local by level programming A problem external as Data

W
number objects. languages is functions. of viewed functions (POP).
o
Global such as as a are Data sequence COBOL, written of FORTRAN

Function-3

r ld
to Local things accomplish Data to and be these

done C, is
other through functions. added whenever necessary.
Object B Data Functions
Provided by JNTU World Team (www.alljntuworld.in)
4
www.alljntuworld.in JNTU World
Basic Concepts of Object-Oriented Programming
Objects Objects place, Class Object can Data Data Inheritance

Polymorphism J ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ be Abstraction Encapsulation a made

contains The The can These This information Abstraction background Since (ADT).
Inheritance another In additional Polymorphism, An upon For sum. concatenation. The

N
operator bank are OOP, operation example access wrapping process

data the a insulation account, the classes If functions user-defined class. basic data, the the
overloading. type is features it. not details of is hiding. consider refers concept operands up use
T
of may and runtime a the making accessible provide table of a data of Greek

the code process to or exhibits the data data to of an used explanations. of the concept entities
an the data the data to term and existing are type inheritance operation operator to in

U
manipulate by interface different functions act or the string the

with means from which in of any class operation. outside of an data the to item direct of then
provides to representing object between objects behaviors without exhibit help into addition that
ability abstraction, that world, the access a of data. oriented single of different the

W
a to the modifying the operation class. for one in only take program

The object’s idea by unit different two essential they class system. those more entire the
behavior is of numbers; it. known are acquire reusability. has data would program than function

o
instances. set features known They to and in one of as handle. the produce
the different encapsulation. data may the is form. which as operation This properties without

r
called program. The and Abstract represent means are instances a behavior code

ld
data third wrapped will including of Data of we a generate

objects hiding string person, an is depends can known object


Types in add the the
by or
of a
a
Provided by JNTU World Team (www.alljntuworld.in)
5
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Shape
Output An cout<<”Srinix cout<<”x”; cout<<x; cout<<”\n”; cout<< << An cin>>x; cin>>x>>y;

multiplied Solution: #include void { } int cout cin cout cout Program
J (two

Output Input x; >>x; main << <<endl<< << Circle Draw endl; takes "less and "Please " prints

<iostream.h> statement and () N 1.1 by takes print statement (circle) takes

Object takes than" the Input College 2. its value "Value x enter value value WAP double the
on the signs) Statement is computer of cursor of an you cursor is used of of to x

T
Engineering”; is used is x integer x on accept " entered and from called

<<x*2 to to computer to to take a y screen. a keyboard. newline. print from in value: insertion

U
newline. an << is input C++ " ".\n"; the integer the <<x; prints
screen.

"; Box Draw from output keyboard. We operator. Draw Object Srinix (Box) can from the on ()

W
use keyboard. College computer the endl keyboard (a of cin

o
manipulator) screen. Engineering is an and input cout print Draw Triangle is
r
statement. instead on an the (Triangle) computer output Object number of \n.

ld
statement. screen.

when it is

Output: Please enter an integer value:


6 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

5 Value you entered is 5 and its double is 10. Operators 1. Arithmetic Operators (+, -, *,
/, %) The five arithmetical operations supported Addition (+) Subtraction (-) Multiplication (*)
Division (/) Modulo (%)
Operations of addition, subtraction, multiplication mathematical operators. Division Rule
Integer/integer=integer Integer/float=float Float/integer=float Float /float=float
Modular a>=b a<b Solution: #include void {

} Output: Program
J main a%b a int a b=4; p= q= r= s= cout<<p<<q<<r<<s;

<iostream.h> = division ()

a%b; 1.2 N b%a; a/b; a*b; a, 10; =remainder b, p, Write q, r, s; a when


T U
program a is divided to demonstrate by by b

W
the C and language division are:
o r ld
literally correspond with their

respective
arithmetic operation.
2 40 2 4
Provided by JNTU World Team (www.alljntuworld.in)
7
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
2. Assignment Operator (=) The assignment operator assigns a value to a variable. a This
operator has any assignment and a This that lost. Shorthand When stored value a a price 3.
In operators. according are can Here (7 (5 (3 (6 (5 Of Suppose (a (a*b (b+4 ((b=2) Important =
J
= -= /= == != > < == >= Relational order course, 5; b; equal to be b; 4) 5) 5;

never statement 2) combination was >= > statement 5) there *= 5) 6) += == is is // // be we a*c)


in used // // // // c) evaluates evaluates units equivalent equivalent increase; evaluates to that

N
stored that (=) a) evaluates evaluates a evaluates or // the to want instead

are variable The // // operation evaluate evaluates Tips! in if assignment is its evaluates
evaluates a=2, + variable other one C++: and some known 1; assigns Boolean until assigns to
result is to to of of b=3 is is to modify to to to to equality whereas to equivalent way: equivalent
greater examples:
false. true. using this a true. these. false. a a to false we as always true. and of to to comparison

T
to = = the result. true the a a moment can false variable a true. (+=, c=6, only

the - / since b; 5; relational integer than the The lvalue since operators takes use to since
value -=, We to numeric rvalue a price compound the most value a is in (2*3 *=, may place (left
U
(the between value not (3+4 a of other = is operation can /=, >= =

important want a constants, value) price equal lvalue) not (==, from > value variable 6) 5 %=,
2*6) be is. to assignment considered is to two * !=, either Here to right and true. + the >>=,
(units the is compare 5. increase;
>, is false. expressions by we rule the value is to variable <, a a <<=, + a

W
performing constant, left, can Boolean >=, right 1); list when at
operators: contained two and use &=, all of <= a. one the in expressions, ) any the assigning
we The ^=, value a this as relational variable, an same valid can |=) part in the operation,

o
operation variable that use expression, rvalue for at is for the and can all the

the the example, other b result (right and equality relational left on only right-to-left (the the

r
including in of operators. of value). rvalue). be fact the an value to operators true
ld
and operation know that assignment The The variables. rule:

currently
or equality value if lvalue false, value
they that The or
is
Be careful! The operator = (one equal sign) is not the same as the operator == (two equal
signs), the first one is an assignment operator (assigns the value at its right to the variable at its
Provided by JNTU World Team (www.alljntuworld.in)
left) and the other one 8
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
(==) is the equality operator that compares whether both expressions in the two sides of it are
equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b
and then we compared 4. The located operand evaluating For evaluates The result. both &&
J
The of possible For ( ( 5. The in c++; (5 (5 a its Increment Logical == ==

evaluating example: example: variable. increment operator logical Operator! its two 5) 5) The at

N
two results && || is operands to (3 it its its operator operators operators

true to (3 > true operands They !(5 || operand. right, 6) the a True True False False a True
True False False and > operator a, is corresponds of 6) == and ) that the because // a
expression are ) is Decrement 5) || evaluates // and && b: true C++ true, && also evaluates

T
equivalent // ( are evaluates (++) !, corresponds the and &&, operator stores

(6 if true, thus with and its only <= a to || && || being are to 4) and operand true Operator the

U
the to Boolean ) thing to false would b: +=1 used to decrement

false value false ( with false true perform and b True False True False b True False True
False ( that when true is be logical otherwise. Boolean because 2, || only (++, to false. false
false. so it && - evaluating does the the =1, when operator --) operation false ). Basically, !true

W
the logical respectively. result Boolean is The both ). expression to

// (--) of following inverse operation evaluates two operands OR. the it increase operation
expressions returns This operation Thus: a True False False False
a True True True False the at && || panel to AND. operation b its are or value b false. the

o
NOT, right reduce false shows is This to opposite of true. !false (5 it
r
themselves. obtain results it, operation by == has the producing one 5) // only a

result evaluates is Boolean true the single true. one results Here value if of

ld
either !(6 false relational operand,

operator value to are <= stored true true. if 4) one the its of
//
if
Provided by JNTU World Team (www.alljntuworld.in)
c+=1; c=c+1; 9
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
are all equivalent in its functionality: the three of them increase by one the value of c. A
characteristic of this operator is that it can be used both as a prefix and as a suffix. That means
that it can be written either before the variable identifier (++a) or after it (a++). Although in
simple expressions like a++ or ++a both have exactly the same meaning, in other expressions
in which the result of the increase or decrease operation is evaluated as a value in an outer
expression they may have an important difference in their meaning: In the case that the
increase operator is used as a prefix (++a) the value is increased before the result of the
expression is evaluated and therefore the increased value is considered in the outer expression;
in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated
and therefore the value stored before the increase operation is evaluated in the outer
expression.
Pre
First increment/decrement then assignment. Post
First assignment then increment/decrement.
Notice the difference:
B=3; A=++B; Ans: B=3; A=B++; Ans: In assigned 6. The different condition 7==5 7==5+2 5>3

a>b Solution: Example Example Program J Example Conditional ? ?


N
conditional A ? a A a 4 contains : : contains ? b : b 4 to 3 one is // 1 2 // :

1.3 // A returns true 3 returns 1, returns // and if B returns Find Find 3, operator the 4,
operator is the Write then B B increased the whichever contains expression 3, contains the the

T
expression since 4, B value a value value is since program evaluates (

increased. 7 ? of 4 before 4 is is 7 of of will : a, not is greater, ) is A A since equal to return


U
and and evaluated equal an its find 5 B. B.

expression value to a is to result1, the or 5+2. greater 5. b. greatest is as assigned false. if than

W
it returning is of not 3. Its two to it format will A. a numbers. value
o
While return is: in Example if that expression condition ? result2.

Downloaded From JNTU World (http://www.alljntuworld.in)

rld
2, the value of B is
is true and a result1 : result2. If
#include <iostream.h>
Provided by JNTU World Team (www.alljntuworld.in)
10
www.alljntuworld.in JNTU World
void main () {
} Output: In value colon) 7. The expression expression For a variable 8. Type to expression int

J
float i The the notation: parentheses: i Both 9. This in a = = = = bytes this

Comma Explicit (int) int sizeof do i; sizeof example, (b=3, typecasting comma previous
operator f ways casting ( specified this = example which f f; int a=2; b=7; c cout<<c;
N
3.14; of a ); 7 = b+2); (char); preceding () would in of that a,b,c; (a>b) is to

is type operator operator was C++. considered. operators expected. type the code be accepts
type would a after operator contain converted ? following was b, casting a The casting
converts with : the or b; the 2 (,) one ( first simplest object: allow and When , expression

T
is the a ) question are was operator value parameter, used code: assign by
b value the you was valid the the (int). one, of to float to set new 7, the 5 mark 7. separate in to

U
while convert Another so which C++. of number which value be

type the expressions was converted variable expression has enclosed two a 3 can discarded
way datum to 3.14 been be or b, b to to more either and would by has between of do inherited

W
an being the in a then to the integer expressions given a favor
contain be type type evaluated same assign evaluated parentheses from type of and or value
value the thing a to b+2 enclosing the variable that (a>b) second another. (3),

o
3. for in C to are language, (()): the C++ a variable was value, itself included

r
value the remainder There is not using expression and only (the true, a. is are
ld
where returns So, to the the one thus is several precede at

lost. functional rightmost after between only the the the Here, ways end, first
size one
the the
This will assign the value 1 to a because char takes 1 byte of memory. The value returned by
Provided by
sizeof is a constant, so it is always determined before program execution. 11
JNTU World Team (www.alljntuworld.in)

Downloaded From JNTU World (http://www.alljntuworld.in)


www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Control Statements
A branch the Selection 1. The through Here, (that optional. age Solution:
#include<iostream.h> void { If
J Program the if programming following ▪ ▪ ▪

Statement is if main() is, condition each above statement based Selection outcome Iteration
iteration Jump statements if { } else {

} two a The (condition) Statements N block). statement 1.4 different 35

categories: if on statements statement statement1; statement2; is and statements language of


changes statements statements true, is WAP The are an young C++’s paths. expression may
T
then examined condition to selection, to check conditional allows works

uses if be statement1 form Here the his enable allows a control age single state whether here.

U
like is or is loops). program iteration, the any the program is

program this: of branch below statement general is state expression statements a executed. a
program. to person of and 35. to statement. execution execute form a choose variable. jump.
W
or is that Otherwise, of to C++ a old compound the cause in

different returns to or program It a if young. can repeat statement: nonlinear the statement2 be

o
a paths statement flow control boolean A one used person fashion. of or of

to statements execution more (if execution route value. will enclosed it exists) All be statements
r
program The said of to based can is in Java’s else executed. advance old curly be

ld
execution upon if clause put (that his control

braces into and


the
is,
is
int age; cout<<”Enter Age”;
Provided by JNTU World Team (www.alljntuworld.in)
12
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
cin>>age; if(age>=35)

} Output: Enter Old


2. A programming. to with 3. A looks The is of mark Solution: #include<iostream.h> void

common true,
J nested The Nested Program the the if main() an like age given.

statements conditions nearest if-else-if the else. cout<<"Old"; else cout<<”Young”;


if statement1; else statement2; ............................. ............................. else statement3;

(condition1) this: if 39 ifs N statement programming is 1.5 if (condition2) an if


When Ladder statement is if are true, Write statement you executed associated then

T
construct a nest program that the that ifs, from is with final the within that

U
is the to the that else main calculate is top the based target

statement if thing to is same executed, down. upon of division to block another remember will
W
As a sequence soon and be as obtained executed.

the if the as or is else one rest else. of that nested by and of of an Nested the a

o
the that student else conditions ifs ladder is is statement ifs not the are with
r
is already if-else-if bypassed. very controlling his always percentage common

ld
associated ladder. If refers the none
It
in
if
{
int mark;
Provided by JNTU World Team (www.alljntuworld.in)
13
www.alljntuworld.in JNTU World
cout<<”Enter mark”; cin>>mark;
if(mark>=60) cout<<”1st Division”;
else if(mark>=50 && mark<60) cout<<”2nd Division”;

J
} Output: Enter 1Switch The execution a statement: st better Division switch

mark Statements else cout<<”3rd else cout<<”Fail”;


N
switch { alternative to 87 if(mark>=40 statement different (expression)

case // break; case // break; ... case // break; statement statement statement Division”; than
value1:
value2:

T
valueN: parts is && a C++’s of large sequence
sequence

U
sequence mark<50) your multi series code way of based if-else-if

W
branch on the statements. statement. value of an It Here
o
expression. provides is the an As general

rld
easy way to dispatch such, it often provides form

of a switch
Provided by JNTU World Team
default: // default statement sequence 14
(www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
}
Program Solution: #include<iostream.h> void main() {
int for(int switch(i) { case cout<<”i break; case cout<<”i break; case cout<<”i break; case

cout<<”i break; default: cout<<”i } } Output: i i i i i i is is is is is is


J zero. one.

1:
two. three. greater greater N than than i 1.6 2: 0:

3: i=0; 3. 3. is is is is is Write i<6; zero.”; one.”;


two.”;
T U
three.”; greater i++) a program than 3.”; to

W
illustrate the use of switch case statements.
orld
Iteration Statements
Provided by JNTU World Team (www.alljntuworld.in)
15
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
C++’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination 1. The controlling The conditional immediately repeated.
Solution: #include<iostream.h> void { } 2. If be even least the Program
J while

do executed while condition main() once, if conditional while the initialization while { //
Increment/ }
int while { cout<<”C++ n++; }
initialization do

loop body loop N n conditional because expression 1.7 expression condition

at Loop = following (condition) (n 0; can all. of is <10) Java’s expression loop However, Write

be decrement its is is good”; is any conditional expression is the most met. true.
T
a true. program Boolean loop. sometimes controlling Here fundamental

U
When The is expression is expression. to false its condition curly

print general a it to while is looping braces desirable begin the is at form:


W
becomes The loop message the with. are statement. body is to

bottom unnecessary initially The execute false, “C++ of do-while the of It false, control is the

o
the repeats loop good” if loop. body then only loop will passes 10 a Its of the

statement be a always times general a single body executed while to the using executes
r
statement of loop form next or the while as block at is: loop line long

ld
least its loop. while is of body will as being once, code

not the its


at
{ // body of loop
Provided by JNTU World Team (www.alljntuworld.in)
16
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Increment/ decrement } while (condition);
Program 1.8
Write a program to print the message “C++ is good” 10 times using do while loop.
Solution: #include<iostream.h> void main() {

int n = 0; do { cout<<”C++ is good”; n++; } while(n<9); } 3. for loop The general form of the

for statement is: for(initialization; condition; iteration) {// body }The for loop operates as

follows:
▪ When the loop first starts, the initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a counter that controls
the loop. It is important to understand that the initialization expression is only executed once.

Solution: #include<iostream.h> void


J Program ▪ ▪ main()
Next, variable it Next, or expression, with is N decrements false, 1.9 each

condition the against the iteration pass. Write then loop the This is a a executing target
evaluated. terminates.
program portion loop process control value. of the to repeats This the print If variable. body
this loop must the until expression of is be message executed. the The the a Boolean loop,
controlling loop is “C++is true, then and This expression. then is then iterates, expression
good” usually executing the 10 first It body an usually times is expression evaluating false.
of the the using tests iteration loop the that for the is loop loop.
executed. increments conditional expression control If
{
int n ;

TU
World
17 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)

for(n=0; n<10; n++) { cout<<”C++ is good”; } } Jump Statements C++ offers following jump
statements:
▪ break statement: A break statement takes control out of the loop.
▪ continue statement: A continue statement takes control to the beginning of the loop.
▪ goto statement: A goto Statement take control to a desired line of a program.
Write a program to check whether a number is prime or not. Solution:
#include<iostream.h> void main() {
int n, i; cout<<”Enter a number:”; cin>>n; for(i=2; i<n; i++) { if(n%i==0) { cout<<”Number is not

Prime”; break; } } if(i==n) cout<<”Number is Prime”; } Output: Enter a number 13 Number is


Prime
The marks obtained by a student in 5 different subjects are input through the keyboard.
The student gets a division as per the following rules: Percentage above or equal to 60 -
First division Percentage between 50 and 59 - Second division Percentage between 40
and 49 - Third division Percentage less than 40 – Fail. Write a program to calculate the
division obtained by the student.
Solution:
#include<iostream.h>
18 Provided by JNTU World Team (www.alljntuworld.in)

Program Program 1.10


JN 1.11

TU
World
www.alljntuworld.in JNTU World
void main( ) {
int m1, m2, m3, m4, m5, per ; cout<< "Enter marks in five subjects " ;
cin>>m1>>m2>>m3>>m4>>m5 ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) {

cout<< "First division" ; } else if ( ( per >= 50 ) && ( per < 60 ) ) { cout<< "Second division" ; }

else if ( ( per >= 40 ) && ( per < 50 ) ) { cout<<"Third division" ; } else { cout<< "Fail" ; } }

Output: Enter marks in 5 subjects 65 65 65 60 70 First division


Write a program to find the roots of a quadratic equation ax2+bx+c=0, where the values of
coefficient a, b and c are given from the keyboard.
Solution: #include<iostream.h> #include<math.h> void main() {
int a, b, c, d; float r1, r2, x, y; cout<<“Enter the coefficients”; cin>>a>>b>>c; d=(b*b) - (4*a*c);
if(d>0)
Downloaded From JNTU World (http://www.alljntuworld.in)
TU
Program 1.12
J N
World
19 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
{ r1=(-b+pow(d,0.5))/2*a; r2=(-b- pow(d,0.5))/2*a; cout<<”Roots are real and the roots are

”<<r1<<” and ”<<r2; } else if(d==0) { r1=-b/2*a; cout<< “Roots are equal and the root is “<<r1; }

else { x=-b/2*a; y =pow(-d,0.5)/2*a; cout<<”Roots are imaginary and the roots are”<<endl;
cout<<x<<“+i ”<<y<<endl; cout<<x<<“-i ”<< y; } } Output: Enter the coefficients 1 -4 4 Roots
are equal and the root is 2
If the three sides of a triangle are entered through the keyboard, write a program to check
whether the triangle is isosceles, equilateral, scalene or right angled triangle.
Solution: #include<iostream.h> void main() {
int a, b, c; cout<<“Enter 3 sides”; cin>>a>>b>>c; if(a+b>c && b+c>a && c+a>b) {
if((a*a+b*b)==c*c || (b*b+c*c)==a*a || (c*c+a*a)==b*b) { cout<<“Right Angled”; } else if( (a==b

&&b!=c) || (b==c&&c!=a) || (c==a&&a!=b)) {


Provided by JNTU World Team (www.alljntuworld.in)
20
Downloaded From JNTU World (http://www.alljntuworld.in)

TU
Program 1.13
J N
World
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)

cout<<“Isosceles”; } else if(a==b && b==c) { cout<<“Equilateral”; } else { cout<<“Any Valid

Triangle”; }
}
#include<iostream.h> void {
}
Solution: #include<iostream.h> void { Solution: Program Program
J main()

main() } else {
}
int for(i=0; { cout<< }

WAP int cout<<“Enter cin>>n;

i, 1.15 n, to s=0;
N 1.14 i;
T
i<<“\n”; i<100 cout<<“Cannot Write Compute ; the i+=2) a value program

U
1+2+3+4+......................+n of form n”; to a valid print triangle”; all
W o
the even integers for a given from value 1 to

100. of n.

rld
for(i=1; i<=n; i++) {
21 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)

s=s+i; } cout<< s; }
Write a program to compute factorial of a number.
Solution: #include<iostream.h> void main() {
int i, n, f=1; cout<<“Enter the value of n”; cin>>n; for(i=1; i<=n; i++) { f=f*i; } cout<<f; }
Write a program to find sum of digits of a number.
Solution: #include<iostream.h> void main() {
int a, n, s=0; cout<<“Enter a number”; cin>>n; while(n!=0) { a=n%10; s=s+a; n=n/10; } cout<<s;
}
Write a program to reverse a number.
Solution:
Provided by JNTU World Team (www.alljntuworld.in)
22

N
Program Program 1.16 J 1.18 Program 1.17
TU

World
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
#include<iostream.h> void main() {
int a, n, rn=0; cout<<“Enter a number”; cin>>n; while(n!=0) { a=n%10; rn=rn*10+a; n=n/10; }

cout<<rn; }
Write a program to check whether a no is palindrome number or not. (A number is said to
be palindrome number if it is equal its reverse
Solution: #include<iostream.h> void main() {
int a, n, rn=0, b; cout<<“Enter a number”; cin>>n; b=n; while(n!=0) { a=n%10; rn=rn*10+a;

n=n/10; } if(b==rn) { cout<<“palindrome”; } else { cout<<“not palindrome”; } } Example 1.19

TU
JN
World
23 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Example 1.20
Write a program to check whether a no is Armstrong number or not. (A number is
Solution: #include<iostream.h> void {
}
Solution: #include<iostream.h> void {
said to be Armstrong number if sum of cube of its digit is equal to that number).
main()
int a, n,s=0, b; cout<<“Enter a number”; cin>>n; b=n; while(n!=0) { a=n%10; s=s+a*a*a; n=n/10;

} if(b==s) { cout<<“Armstrong”; } else { cout<<“Not }


Example
J main( int for(n=2; {

N ) n, 1.21 i ;
TU
Write Armstrong”; a program to print all the

W o
prime numbers from 1 to 500.

n<=500; n++)
for(i=2; i<=n-1; i++) {
if ( n% i == 0 )
rld
{ break ;

24 Provided by JNTU World Team (www.alljntuworld.in)


www.alljntuworld.in JNTU World

} } if ( i == n ) {

cout<<n<< "\t" ; } } } Array Collection of similar data types stored in contiguous memory Syntax
is:Data_type array_name[size];
i.e. int a[20]; means a is an array which can hold 20 integers. can hold 16 character. An array
index always starts from 0 the In a[0] a[1] And Structure

A struct { } ; struct Here members. b1.name b1.price structure J the size is is a[19]
b1, above book book the the char float int of – b2 - price second is first name

N
To the pages is b1, the and name example: price a access array.

element.
collection b2, of last b3 of ; element.............

T
book ; ; b3 book are element a ; structure structure b1. b1. of dissimilar of the
U
member variable array data a. we of types. type need book. dot(.)

W
And operator. and name, location char index nm[16]; price is of
o
known and last means element pages as array.

r ld
nm are is is called n-1, an array where structure

which n is
Provided by JNTU World Team (www.alljntuworld.in)
b1.pages – price of book b1. 25
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Union
A union {
} unionbook Here Here members. b1.name b1.price b1.pages Difference Function A ; union

function J 1) 2) 3) b1, b1, book char float int Syntax:

All be Structure to members. struct }Here of(x)+sizeof(y). is – b2 int float - – b2 price a name

N
To accessed the pages is price b1, the collection and struct { //Data } x;

between name price a and access y; example{ b2, self-contained total memory of members
b3 of of ; Structure allocates book b3 structure_name b3 ;
types ;
are book book at a memory ; are of union union once. structure b1. dissimilar b1.

T
b1. union of allocated the member the variable block required memory

U
variable structure and datatypes. of of we is statements union
by type equal need of size can
the

W
type book. dot(.) book. that 1) 2) 3) operator. perform And Syntax:

In time. Union maximum the union }Here size int float a union. union { //Data }

x; of union name, memory y; example{ float a allocates coherent union_name types memory

o
only is price more allocated Union one the and task required than member
r
memory pages of size is some sizeof(y), by of can are the integer. kind. equal

ld
called be member used Basically because to union at the of

a
Provided by JNTU World Team (www.alljntuworld.in)
a function consists of three parts: 26
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Function prototype: Function prototype is the skeleton of a function.
Syntax Example: Function Syntax Example: Function which Syntax Return_type { //Function

} Call reference.
Solution: Call #include<iostream.h> void void {
} void {
is: return_type function_name(type of arguments);
int add(int, int); void display(void);
Calling: A function gets called when the function name is followed by a semicolon. is :
function_name(list of arguments);

Program
J ▪ ▪ ▪ swap(int, swap(int by by main() one is:

In address In argument Memory int swap(x, cout<<x<<y<<endl;


int a=b; value value sum(x,y); call call N Body or Definition: x=5, t=a; 1.22

function_name(list more a, int); by by and y=7; y); of int can value, value changes. the

T
statements Write b) call search(mark); be argument saved A by of value

function a actual reference program if may of we of is the arguments arguments passed call
U
is be argument defined present. a to function during swap do

with when is not function by two their passed reference.


Call #include<iostream.h> void void {

W
} void { function changes. integers types)
swap(int swap(int by main() calling. during int swap(&x, cout<<x<<y<<endl;

int *a=*b; refernece name But x=5, t=*a; function *, *a, using in y=7; is int call int &y);

o r
followed *); *b) call by calling. reference by by value In a pair of

ld
braces in
call by reference
value of actual
and call by
b=t;
*b=t; cout<<a<<b;
cout<<*a<<*b;
Provided by JNTU World Team (www.alljntuworld.in)
27
www.alljntuworld.in JNTU World

} } Output: 5 7 Default Consider float We third int int int int J 57

Add(int Add(int Add(int Add(int ▪ ▪ ▪ can amount(int argument. C++ In argument Default call

N
arguments the such i, i=5, i=0, i=2, allows the int following int int int

cases values j=5, We above principal, in j); j, j=5, us int must int the function to are int k=10);
T
k=10); function function function call k=10); add specified int a function

U
period, assigns default prototype: by call. when amount float a

values without // // // // default legal illegal illegal legal the rate=0.15); (5000, function from
W
specifying value right 7);. Output: 7 7 to is 5 5

Here the declared. to all left. parameter its default arguments.

o r
value which 0.15 does will not be have assigned a
ld
matching
to the
Provided by JNTU World Team (www.alljntuworld.in)
28
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Assignment-1
Short Type Questions

Long J 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

Type What What Can Why Define Define Differentiate Differentiate Define Differentiate Why
What programming? Describe Describe What Explain Write Write Using Write Write Write Write
N
fibonacii Write by Write by that 2×2 the adding Questions matrix. we

column can’t structure is are is a a a a both a a structure, a user. is array keyword. loop.
program program program program program initialize function program a pointer? program
sequence the different structure the the we all recursive Write and and basic elements between
between between advantages compare is difference write prototype, unions? used

T
Differentiate to to to to to pointer? to the types concepts to the are and find
find check reverse print convert and diagonal instead print a syntax = while const 0 in
structures? how program factorial largest and of and all non of that whether between operators

U
a integers fibonacii function using a of to loop ==. 1 and number

recursive of of 2×2 between row, respectively.) object element define among for union? of to
volatile. and unions? matrix a a a loop. find number from calling procedure number. new in
using sequence oriented do and a function call c++. is Write addition list while into 1 column

W
declare obtained function by to and of is 3×3 n the value
programming integers loop. Armstrong to using function up oriented of a matrix, element
difference find two structure? to by and recursion. recursion, gcd summing 50 stored complex
call definition where or terms. programming is of by between not? briefly.

o
obtained two in reference. where a an number. all integers. (Assume, new

r
with array. diagonal structure by the row suitable adding and value element first
ld
elements object and examples. of all two n union. elements

is is terms obtained oriented


supplied
of given of
in
Provided by JNTU World Team (www.alljntuworld.in)
29
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Chapter 2 Class and Object A class is a way to bind the data and its associated functions
together. It allows the data and functions to be hidden, if necessary, from external use. A class
declaration is similar syntactically to a structure.
General form of a class declaration is:
class class_name { private: Variable declaration/data members; Function declaration/ member
functions;
protected: Variable declaration/data members; Function declaration/ member functions;
public: Variable declaration/data members; Function declaration/ member functions; };
Points ✓ ✓ ✓ ✓ General Solution: #include<iostream.h> Program
J ▪ ▪ ▪ ▪ to

The declared Wrapping encapsulation. By Private Header Class Member void steps

N remember! default 2.1 variables main definition data files to function


T
inside Write function the of write members declared data data a a class a

definition program and C++ members are can inside function program known be

U
to the and accessed find class and as member using member

sum function definition by class the of function Private the Protected and Public class
W
functions. two functions class. its into and also. are members

derived integers members of a known object: members a single that class classes. as can

o
are using can unit are data wrapped can be private. be (i.e. class
r
members accessed accessed be class) accessed and inside is and from object.

ld
only known the by the from class. outside own functions as

within class
data the
30 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
class Add
{
int x, y, z; public: void getdata() { cout<<”Enter two numbers”; cin>>x>>y;

}; void {

} void {

} void {

} Output: Enter 11 A member J (i) (ii) Add Add main() two } void void z=x+y;

cout<<z;

N
Add a.getdata(); a.calculate(); a.display(); :: :: numbers function
calculate() display()
Inside Outside a; display(void); calculate(void);

T
the 5 can side class 6 be the defined: definition class definition

U W
using scope resolution operator
o rld
(::).

31 Provided by JNTU World Team (www.alljntuworld.in)


Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
▪ Here in the above example we are defining the member function getdata() inside the class
definition. And we are defining the member functions calculate() and display(), outside the class
definition using the scope resolution operator.
▪ Here void Add :: calculate() means the scpoe of member function calculate() Add or we can
say the function calculate() belongs to the class Add. :: is operator which tells the scope of a
member function.
▪ We cannot directly call a function, we can call it using object (through . operator) which the
function is declared.
How to access member of a class? To access member of a class dot operator object-
name.data-member and object-name.member-function
Application of Scope resolution operator ▪ It is used to specify scope of a member ▪ It is
used to access a global variable.
Object as Function argument
Program Solution: #include<iostream.h> class time {
int public: void
J { hours=h; minutes=m; } void void }; void { Downloaded From

JNTU World (http://www.alljntuworld.in) 2.2 Write a program

display(void); gettime(int minutes;


N hours, sum(time,
TU
time); h, int m) to add time :: sum (time t1,

time t2) is two used. (::)

W o
function. time i.e. objects (in the form hh:mm).
r ld
the is scope inside of the resolution the class

class in

minutes=t1.minutes+t2.minutes; hours=minutes/60;
Provided by JNTU World Team (www.alljntuworld.in)
32
www.alljntuworld.in JNTU World
minutes=minutes%60; hours=hours+t1.hours+t2.hours;
} void {

} Output: 2 3 Addition Array Collection Solution: #include<iostream.h> class {

} void time :: display() { cout<<hours<<” : ”<<minutes<<endl;

main()
time T1, T2, T3; T1.gettime(2,45); T2.gettime(3,30); T3.sum(T1, T2); T1.display(); T2.display();
cout<<"Addition of above T3.display();
: 45 : 15
of above two time is 6:15
Program
J Employee of char int public: void void object of

N 2.3
age; name[30];
T
getdata(void); putdata(void); similar Write types a program of object two to is

U
known input time is name as ";
W o
array and of age objects. of 5 employees and

r
display them.
ld
Provided by JNTU World Team (www.alljntuworld.in)
}; 33
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

void Employee:: getdata(void) { cout<<”Enter cin>>name>>age; } void {

cout<<name<<”\t”<<age<<endl; } void {
} Output: Enter Enter Enter Enter Enter Rajib Sunil Ram Bibhuti Ramani Constructor
J
▪ Employee:: main() Name Name Name Name Name Employee int for(i=0; { }

for(i=0; {

N
} A constructor i; and and and and and Name i<5; i<5; e[i].getdata();

e[i].putdata();
25 27 23 26 32

putdata(void)
Age: Age: Age: Age: Age: e[5]; i++)

T
i++) and Rajib Sunil Ram Bibhuti Ramani is a Age:”; special 25 27 23 26 32

U W
member function whose task is to
o r ld
initialize the object of a class.

▪ Its name is same as the class name.


Provided by JNTU World Team
▪ A constructor does not have a return type. 34
(www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
▪ A constructor is called or invoked when the object of its associated class is created.
▪ It is called constructor because it constructs the values of data members of the class.
▪ A constructor cannot be virtual (shall be discussed later on).
▪ A constructor can be overloaded.
There three types of constructor:
(i) Default Constructor (ii) Parameterized Constructor (iii) Copy constructor
Default Constructor
The constructor which has no arguments is known as default constructor.
Solution: #include<iostream.h> class {
}; Add::Add() {

} void {

} void {
} void { Program
J Add Add main() Add

int public: Add(); void void x=6; y=5;


z=x+y;

cout<<z; :: :: N
display(void); calculate(void);
2.4 x, calculate() display()
TU
y, z; Demonstration of default // Default

Constructor. Constructor

World
Add a; a.calculate();
35 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

a.display(); } Output: 11 Note: default respectively.


Parameterized The constructor Solution: #include<iostream.h> class {
}; Add {

} void {

} void { } Program
J constructor :: Add Add Add Add(int Here int public: Add(int,

void void x=a; y=b;


z=x+y;

cout<<z; constructor :: :: N x, calculate() display() 2.5 in and display(void);


calculate(void); y, a, the z; which int); int add constructor Write above b) Add them. takes

T
program a () will program some be argument when called

U
to the automatically initialize is statement known
W
two as Add parameterized and integer a; value will execute of

variables x constructor.

o r
and (i.e. y will using object be parameterized is set created),
ld
to 6 and the 5

void main() {
Provided by JNTU World Team (www.alljntuworld.in)
36
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

Add a(5, 6);


a.calculate(
);

} Output: 11 Note: creation), will A If object-name What The an Copy The constructor. Solution:
#include<iostream.h> class { Program the parameterized
J object. be (i) (ii)

constructor initialization Add constructor Constructor is Here set a.display(); Implicitly:

Explicitly int public: Add() Add(int { { } Dynamic the to It N x, 2.6 is in 5 (value-of-

argument); y, parameterized achieved Copy and z; the a, which constructor of Write has int

6respectively. :Add Initialization Add an above given b) one takes object by a=Add(5, a(5,
T
a argument, parameterized program integers program reference 6); can

U
constructor at the be 6); of to called: time when initialize into an then

to to object? its Add of constructor. initialize a we the own execution new an can (int, statement
W
class object. object also int) two as of will use argument program and

integer be object-name=value-of-argument; Add called add a(5, is is them. variables

o
automatically known known 6); will as as be dynamic copy using executed and
r ld
constructor. parameterized value initialization (i.e.

instead of x object and of of y

x=a

;
y=b
;

37 Provided by JNTU World Team


(www.alljntuworld.in)

Downloaded From JNTU World


(http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

} Add(Add &); void calculate(void); void display(void); }; Add :: Add(Add &p) {

x=p.x; y=p.y; cout<<”Value of x and y for new object: ”<<x<<” } void Add :: calculate() {

z=x+y; } void {

} void {
} Output: Value 11 Note: parameterized and will What If a J program be

6respectively. Add main() of Here is called cout<<z; Add Add b.calculate(); b.display(); x

N
Constructor :: and display() in a(5, b(a); contains and the y constructor

for 6); the above Now new content more Overloading? object program when
T U
Add than of the are (int, object one when statement 5

int) constructor, and a the will will 6

W
statement be be Add copied called then b(a) automatically Add

constructor into ; and ”<<y<<endl; a(5, 6); will will execute, object b. is
o rld
execute and value the copy said to be

(i.e. object creation), the of x and y will be set to 5 constructor Add(Add& )


Provided by JNTU World Team (www.alljntuworld.in)
overloaded. 38
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Destructor
▪ It is a special member function which is executed ▪ Its name is same as class name but it
should ▪ It cannot be overloaded as it takes no argument.
▪ It is used to delete the memory space occupied ▪ It has no return type.
▪ It should be declared in the public section of Program 2.7 Demonstration of Destructor.
Solution: #include<iostream.h> class XYZ {
int x; public: XYZ( ); ~XYZ( ); void display(void); }; XYZ::XYZ( ) {

x=9; } XYZ:: ~XYZ( ) { cout<<”Object } void {

} void {
} Output:
J XYZ::display() main()

cout<<x;

XYZ xyz.display(); N xyz;


T U
is destroyed”<<endl; Downloaded From JNTU

W
World (http://www.alljntuworld.in) be the preceded by class.

automatically an object.
o
by the when symbol an ~.

r
object is destroyed.
ld
9 Object is destroyed.

39 Provided by JNTU World Team (www.alljntuworld.in)


www.alljntuworld.in JNTU World
Inline function
In the to Why Whenever control, several when expanded Solution: #include<iostream.h> inline
void { int cout<<“ cin>>r; cout<<” } inline { return(3.14*a*a); } Output: Enter 7 153.86 Program
J C++, be r; point ▪ ▪ ▪ ▪ ▪ main() expanded inline the float float the we A It It Its

The time, Enter Area a Value of executes can function 2.8 in function

N significant can body a area(int); area inline each function a function is: be

huge the line create in (int of Write “ does recursive. << invocation. Value line wherever

keyword r: which faster amount is a) area(r); not short is amount called, rather is a called, of
T
used? program is than contain r: expanded functions is it of ”; than This

rather preceded is other of control time called. if time called, process else, to

U
member than will that in find jumps is by a switch, be precede

line required. are jumping function is area lost. similar function. not when to loop, definition of
Therefore actually its to definition. it For a to definition is goto circle
W
the using called functions called, definition statement. part we

using a is function-like with of called declare rather having the inline the of inline function.

o
inline their function, such short function. macro. function. code keyword.
r
function definition During function is To expanded as cause this inline if definition

ld
jumping it a Downloaded From JNTU World

(http://www.alljntuworld.in) in line at function


of is called so that is
40 Provided by JNTU World Team (www.alljntuworld.in)
www.alljntuworld.in JNTU World
Friend Function
Solution: #include<iostream.h> class {
}; Add {

} int {

} void {

} Output: 11 Note: Program


J calculate(Add ▪ ▪ ▪ ▪ ▪ ▪ :: main() Add Here

Add(int Scope Since It It data It Usually int public: Add(int, friend x=a; y=b;
return(p.x+p.y);

Add cout<<calculate(a); can can 2.9 cannot N x, the a(5, members y, its be
be int a, of function z; it Demonstration int); scope int 6); called declared a p) calculate(Add

T
has directly friend b) the by is like calculate not function objects using either

access a normal inside object p); in of as the () is private the Friend is arguments.

U
not function data called through class, inside or members
Function. directly public it without the cannot dot class operator. part like like using

W
be in normal of other called which the any class member object.

o
function using it is definition. declared. the as function object it is declared of
r ld
and that it class as can friend. access the

41 Provided by JNTU World Team (www.alljntuworld.in)


Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Friend Classes It is possible for one class to be a friend of another class. When this is the
case, the friend class and all of its member functions have access to the private members
defined within the #include <iostream.h> class TwoValues {
int a; int b; public: TwoValues(int i, int j) { a = i; b = j; } friend class Min; }; class Min {

public: int min(TwoValues x); }; int Min::min(TwoValues x) {

} int {

} Output: 10 Note: TwoValues J main() In return TwoValues Min cout return this
N
class. m; << example, 0; x.a m.min(ob); < ob(10, x.b ?

T U
class x.a 20); : x.b; Min
Wo
has access to the private variables a other

class.

rld
and b declared within the
42 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Static Data Members
Solution:
#include<iostream.h> class {
}; A {

} int void {

} void { Program ::
J A:: A()

▪ ▪ ▪ ▪ ▪ A:: A:: A q=10; The When only Hence Unlike each member All Normal variables.
int static public: A(); void void p=5;
p++; q++;
cout<<p<<”\t”<<q<<endl; incr()
display() N static p; 2.11 data display(void); one incr(void); object. int we

static regular data exists. q; copy member variables precede Demonstration variables No

T
members of data Thus, matter that of a are members, member a all variable
U
are initialized class how objects are called of preceded many

called variable's static will individual class of to exist that objects zero object data variables. by
declaration class and before the members. copies of variable that keyword use a

W
class the of that all first with a objects but are same static static

object created, static, static variable. is member of known is the data we


o
created. only class are members as variable one telling static will copy share

r
member.
ld
the are are of compiler not that a called static made

variable.
class data that
for
} void main()

43 Provided by JNTU World Team (www.alljntuworld.in)


Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
{
A a1, a2, a3;
} Output: 6 6 6 Note: separate of Static Solution: #include<iostream.h>

class { };
Program
J q ▪ ▪ ▪ ▪ ▪ ▪ ▪ exists ABC Here Member a1.incr(); a1.display();
a2.incr(); a2.display(); a3.incr(); a3.display();
A in functions.) It The A There A Finally, public: static 11 12 13

2.12
N
copy is static static static for the accessed function p all int cannot is

of same they member member function the a add(int, p function/method Demonstration

T
normal exists). objects. cannot class. name by be class a can function
function int); static But variable, (Of is be have preceded name q declared course, and is does

U
may of access static and whose a static non-static not not by

global not as variable to the be const have member value by only virtual. keyword functions
object’s this or version other or is volatile. member, 5 pointer.

W
function. for static name static. of and all the 3 members data i.e.
whose objects same class-name::function-name; may initial function. a1, (functions be

o r
a2 value accessed and is or a3 10 variables) by (For and static a

ld
each single declared member object, copy

Provided by JNTU World Team (www.alljntuworld.in)


int ABC:: add(int a, int b) { 44
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

return(a+b); } void main() {

ABC abc; int res; res=ABC :: add(30, 40); cout<<res; } Output: 70

TU
JN
World
45 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Assignment 2
Short Type Questions
1. What is friend function? State its properties. 2. What is inline function? 3. What is static data

members and static member function? Long J 4. 5. 6. 7. 8. 9. 10. 1. 2. 3. 4. 5. 6.

7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. Type How Differentiate What Define Define Define
What Explain What WAP WAP WAP (char[]). Define initialize What What What What Define
object. What A What answer How Create and input Write account class mechanism run What

N
function Questions time. emp_da. a does contains to to to to are is do is

is is is is is a is member default dynamic copy a a a with function scope the a a class default find
add a complete initialize add class number class its complex you the data constructor?
destructor? copy an can variables difference to constructor two greatest suitable and mean two
between inline difference emp_da student called resolution a members constructor create return

T
argument? constructor? function initialization public prototype, time the

object? and string number. program function by Employee example. attributes using of Explain
more an objects balance. static with between macros Explain is method 2 object. with of and
between array operator? 20% How no’s with Write constructors Discuss a member than calling

U
to differ data class member of an with (in Explain using a of of
and about create which and The object. named an public, class The example. one the a
Account the members? from can an method example. inline and program with State display
class attributes variables form string value. copy example. emp_salary. differs contains a
function? the be private How definition as a a class and function. any preprocessor accessed?
and suitable of show role constructor objects. the Explain. object overriding to it from display

W
Discuss. hh two called object as is and of protected read should

details : () achieved? roll mm a with applications. a example. to Provide is protected The copy
structure? and them. Account number initialized display :ss). suitable regarding with be Macro?
and array print constructor attributes initialized an a method the and suitable size members a
o
with appropriate examples. complex by 25 initialized name. should following

protected students such overloading? through example. while of Generate number as be class?

r
method attributes. emp_id, initializing given of constructor. attributes constructors. a
ld
Downloaded From JNTU World (http://www.alljntuworld.in)

string
an object and
using class and
Explain your
emp_salary to take user class.
such as The Provide a by the user at
a pointer attribute of a class for which the memory allocation takes place at the run time.
Provided by JNTU World Team (www.alljntuworld.in)
46
www.alljntuworld.in JNTU World
Find Errors (if any) and correct them:
1. class My_College
3. class F {
{ float cgpa;
int p; public:
public: float My_College();
friend void print(){ } };
}; void main() 2. class ABCD
{{
print(); public:
} int INT()
4. class M { { return(1);
char nm[50]; }
public: }; void main() {
cout<<INT(); }
Find Output:
1. #include<iostream.h>

J 2. Downloaded From JNTU World (http://www.alljntuworld.in) int void {

#include<iostream.h> void {

main()
N x=5; main()

int cout<<x<<::x;
int char if(a, cout<<”Congratulations!!”;
x=4;
a=2, b, x=1, x, b=1;

T
y) y=0;

UW
3. show();

};
#include<iostream.h> int x=5;

orld
void main() { (5/2)? cout<<”Hi”:cout<<”Hello”; }
4. #include<iostream.h>
void main() {
Provided by JNTU World Team (www.alljntuworld.in)
int a, b; a=(b=7, b+2); cout<<a; } 47
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)

Chapter 3 Inheritance It from called Base-Class When Class class { }; The class access
public In of is
J all the the ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ access which access cases, derived-

class-name inheritance derived derived a is specifier process Single Multiple Multilevel


Hierarchical Hybrid // When public members When members When become class the body

N status properties the specifier default Access inherits class. the members

Inheritance the a class. Inheritance of by base's is protected base Inheritance uses class of of

of Inheritance private base access which in Inheritance the the the Inheritance Control must
T
class' another, this are the private class base-class derived base of object :

specifier inherited absence general by access members be the access is class default either
elements derived inherited the of class. can base-class-name form: one become members of

U
for specifier members is be public, of if an called class a class,
the the broadly remain explicit base by derived private derived base using acquires private, is

inside and of class protected, classified private access the all class the members class. the

W
class is protected base the or private public, and derived

specifier. to protected. properties is into: class the public a the of class. all base access
members class class the become public and derived If If and of is to no the specifier, object

o
protected determined which are members members access of derived class.
the not of properties all base another specifier accessible members class public of of by

r
become the the access. is class. are is and a derived base by present, struct, of

ld
inherited The protected

protected
members The the become base- class. class
then
base the is
Provided by JNTU World Team (www.alljntuworld.in)
48
www.alljntuworld.in JNTU World
Single Inheritance
In a single inheritance the derived class is derived from A B
(Single inheritance)
Program 4.1 Example of single inheritance with Solution: #include <iostream.h> class A {
int i, j; public: void set(int a, int b)
}; class {

{ i=a; j=b; } void show()


J B : { } int public: B(int { } void { cout } public cout k=x;
T
N k; showk() << x) << A k i << << " "\n"; " << j << "\n";

U W
base a single class base access

class.
o
control as public.

rld
};
49 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
void main() {
} Output: 1 3 Note: class. base Solution:

#include class }; class { { Program 2


J class. A B So Here : B b.set(1, b.show();

b.showk();
int public: void { i=a; } void { }

int public: B(int { } void private cout k=x; object <iostream.h> b(3);

N 4.2 i, k; all j=b; set(int show()

showk() j;
x) << public A 2);

T
of i Example << derived a, " and " int << b) protected j of class << single

U
"\n"; cannot inheritance members directly of with access the
W
base base the class class member become access function

o
control private and as members private.
r ld
data members of the derived of the

Provided by JNTU World Team (www.alljntuworld.in)


{ cout << k << "\n"; } 50
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

}; void {

} How Private function/methods Multiple In Multilevel In Syntax: class { Data Member };

class { J multiple multilevel main() members base-class-name1 derived-class-

name to B b.set(1, b.show(); data access functions b(3);


N
Inheritance inheritance Inheritance inheritance members 2); the

T
//******Error****** of the private derived class base of : visibility base data
U
B class. class is A derived class member mode (Multiple is

derived can from base-class-name be of Inheritance) D B from a base accessed class more

W
A class and than C by in a class derived one derived base C is
o r
class derived class. class? by from using the public class

ld
B.

member

Data members Member functions


51 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

}; class derived-class-name1: visibility mode derived-class-name { Data members Member

functions }; Note: visibility mode can be either private, public or protected

Hierarchical In Syntax: class { Data Member }; class { Data Member

J hierarchical members members base-class-name

derived-class-name1 functions

N T
functions Inheritance inheritance several : visibility
U
classes (Multilevel mode can base-class-name

AB
W
be C inheritance) derived from a single base
o
class

rld
};
52 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

class derived-class-name2: visibility mode base-class-name { Data members Member

functions }; Note: visibility mode can be either private, public or protected


A
B
C (Hierarchical inheritance)

Hybrid It Constructor When first, called their is J the order followed first, an

N
mixture inheritance object of followed derivation. and by of of the one
T
Destructor a by derived derived or the Destructor more base class class'

U
above Execution A D B class' is functions constructor. created,

inheritance. destructor, in are Inheritance if the When executed if D


World
C

base class contains a constructor, it will be called a derived object is destroyed, its destructor is
it exists (i.e. constructor functions are executed in
in reverse order of derivation).
Provided by JNTU World Team (www.alljntuworld.in)
53
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Program 4.4 Constructor and Destructor execution in single inheritance.
Solution: #include class {
}; class {

}; void {
} Output: Constructing Constructing Destructing Destructing Note:
J main()

base

derived: In public: base() { cout } ~base() { cout }


public: derived() { cout } ~derived() { cout } derived the <iostream.h>

N derived base above << << << << base derived public "Constructing
T
"Destructing "Constructing "Destructing ob; program, base first base\n";

derived\n"; base\n";

U
derived\n"; base's constructor is executed
Wo r
followed by derived's. Next (because

ld
ob is immediately destroyed in this program), derived's

destructor is called, followed by base's.


Provided by JNTU World Team (www.alljntuworld.in)
54
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Program 4.5 Constructor and Destructor execution in multilevel linheritance.
Solution: #include <iostream.h> class base {
public: base() { cout << "Constructing base\n"; } ~base() { cout << "Destructing base\n"; } };

class derived1 : public base {


public: derived1() { cout } ~derived1() { cout } }; class derived2: { public: };

J derived2() { cout } ~derived2() { cout } N << << << << public

"Constructing "Destructing "Constructing "Destructing derived1


T
derived1\n";

derived2\n";

derived1\n";

U
derived2\n";
World
void main() {
Provided by JNTU World Team (www.alljntuworld.in)
55
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

derived2 ob; } Output: Constructing Constructing Constructing Destructing Destructing


Destructing #include class {
}; class { }; class Solution: Program
J base1 base2 derived: public: base1() {

cout } ~base1() { }

public: base2() { cout } ~base2() { cout } cout <iostream.h> N 4.6 derived2

derived1 base << << << << base derived1 derived2

public "Constructing "Constructing "Destructing "Destructing Constructor base1,


T
public base2\n"; base1\n"; and base1\n";

base2\n";

U W
base2 Destructor execution in

multiple inheritance.
orld
{
public:
Provided by JNTU World Team (www.alljntuworld.in)
56
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

derived() { }; void {

} Output: Constructing Constructing Constructing Destructing Destructing Destructing Note:

derived's Passing So cases standard base passes derived-class derived-constructor { } Here,


J
a colon far, main() class? base1 where In none along separates cout }

~derived() { cout }

N
derived // the Parameters inheritance parameterized body The derived

base2 base1 through above << << of only base1 base2 derived constructor arguments of the
"Constructing "Destructing ob; answer derived the the preceding program, (arg-list) baseN list.

T
derived derived to is constructor Destructors to declaration constructor

Base-Class to are one derived\n"; : use constructors class' examples derived\n"; base1(arg-

U
list),base2(arg-list), class' the or an names constructor more
syntax. expanded constructor is are Constructors shown have called base-class of are

However, the included here: called form in declaration base requires reverse of constructors. in

W
classes how constructor the order order, one do derived from

......,baseN(arg-list) inherited of or you right derivation, the more functions pass The class's

o
base-class to by parameters, arguments general left. the constructor left that
r
derived specifications, to form require right, to we a class. of declaration constructor

ld
simply this as arguments. specified Notice expanded and

use that that


that in the In in
a
the base-class specifications are separated from each other by commas, in the case of multiple
Provided by JNTU World Team (www.alljntuworld.in)
base classes. 57
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Program 4.7 Passing Parameters to Base Class Constructors in Single Inheritance.
Solution: #include <iostream.h> class base {
protected: int i; public: base(int x) { i=x; cout << "Constructing base\n"; } ~base() { cout <<

"Destructing base\n"; } }; class derived: public base {


int j;
}; void {

}
J main()

public: derived(int { j=x; } ~derived() { cout } void { cout }


derived ob.show(); N cout show() << << "Destructing i ob(3, << << x, "

T
"Constructing " 4); int << y): j << base(y)

derived\n";

"\n";
U
derived\n";

World
58 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Virtual Base Classes An element of ambiguity can be introduced into a C++ program when
multiple base classes are inherited. For example, consider this incorrect program:
What is Multipath Inheritance? Multipath Inheritance is a hybrid inheritance (also called as
Virtual Inheritance). It is combination of hierarchical In PARENT1 inherited Problem There time

like Why Suppose PARENT2 CHILD int int int J j k i(two Diamond. Multipath ( (

error one Ambiguity one is class copy an from copy GRANDPARENT and in copy

N
[Ambiguity]. has int inheritance ambiguity have Multipath PARENT1 of

PARENT2 j both of a of Inheritance data data data data data Problem PARENT1 member
T
member: member member problem. member and int If Inheritance which

we int i has multiple in see there and j GRANDPARENT) multipath are PARENT1) a

U
PARENT2) int [Ambiguity int When the data PARENT2. inherited

k. k inheritance. structure is CHILD int we member GRAND a I (Virtual) run one int in from
class of Multipath program CHILD i(Duplicate Multipath int int PARENT base
W
GRANDPARENT. which i Inheritance? i. PARENT1 with class

Inheritance] is Inheritance Copies inherited such GRANDPARENT. has type Third of a int

o PARENT
from then inheritance, data Derived i) int we PARENT1 member
r
k find Two class that it Downloaded From JNTU World (http://www.alljntuworld.in) derived

2
CHILD gives there

ld
int i int and which class is

a compile is shape
j. Another PARENT2.
Provided by JNTU World Team (www.alljntuworld.in)
59
www.alljntuworld.in JNTU World
This is ambiguity problem. In CHILD class have two copies of Base class. There are two
duplicate copies of int i of base class. One copy through PARENT1 and another copy from
PARENT2. This problem is also called as DIAMOND Problem.
Program 4.7 Demonstration of ambiguities in multipath Solution: // This program contains
an error and will not compile. #include <iostream.h> class base {
public: int i; }; class {

}; class {

}; class {

}; void {

derived1 : public base

public: int j;
J derived2 derived3 main() public: int public: int derived3 ob.i ob.j
ob.k ob.sum cout cout cout N k; sum;

= = = << << << 10; 20; : : 30; public public ob.i ob.j ob.sum; = ob; // ob.i this << << + derived1,

T
base " " is ob.j "; " ambiguous, << // + also ob.k ob.k; public ambiguous, << //
U
" i which ambiguous "; derived2

i???
which here, i?

W
too inheritance.
orld
}
60 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
As the comments in the program indicate, both derived1 and derived2 inherit base. However,
derived3 inherits both derived1 and derived2. This means that there are two copies of base
present in an object of ob.i copies ambiguous. There operator Remove In ob.i ob.sum cout
ob.derived1::i ob.sum cout As base. there have Remove When the virtual virtual derived3
Solution: #include class }; { Program
J Program type we base = = << <<

guessed, base However, 10; some 10; two are can when of when derived3. ob.i ob. public: int =
= class contains <iostream.h> to Ambiguities which ob.i ob. Ambiguities base

N two i; or 4.8 see, 4.7, derived1::i i << way and derived1::i it it + more = from

is " present is the ob.j ways 10; is this i because "; yes. Remove to is Therefore, manually
inherited. only inherited. will being ambiguous being prevent + objects solution This ob.k; to be
T
<< one using in using + remedy the replaced referred " solution present

ob.j Ambiguities object "; copy select are two in We respectively raises For :: virtual + an
scope statements was derived ob.k; of accomplish copies example, one expression the ob, to,

U
in is by base: a applied, achieved an deeper base the there i.

preceding resolution using The object from from one class: here second are issue: this like
the virtual being in a using derived common two derived1 is program. by program operator:

W
What another is virtual included preceding base ob.is! to from use if

base or class. base only has As The those the virtual version in we class, manually the one
derived3? classes. one first objects can base base copy in of we is see, derived2? the to

o
can class. class' selected of by The apply the example base prevent
r
declaring answer, name statement Because is the derived1's actually program

ld
multiple with scope the as there you the base is required?

resolution inherently
version copies probably
in keyword are class which two
as of
of Is

class derived1 : virtual public base {


Provided by JNTU World Team (www.alljntuworld.in)
61
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

public: int j; }; class derived2 : virtual public {

public: int k; }; class derived3 : public derived1, {

public: int sum; }; void main() {


derived3 ob; ob.i = 10; // now unambiguous
ob.j = 20; ob.k = 30; ob.sum = ob.i + ob.j cout << ob.i << " "; // cout << ob.j << " " << cout <<

ob.sum; } As derived1 only is perfectly J we one can and copy

N
see, valid derived2 of the and base keyword unambiguous. to have
T
be + inherited present. unambiguous virtual ob.k base ob.k; public << //

U
precedes " Therefore, unambiguous base "; derived2 as the
W
virtual, in rest derived3, of any the multiple inherited there is

o r
inheritance only class one specification. copy involving of base
ld
them Now and will that ob.i cause both

= 10
62 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Assignment 3
Short Type Questions

Long J 1. 2. 3. 4. 5. 6. 1. 2. 3. 4. 5. 6. Type Define Write List Define How class

class Private class Describe How the Give required? Explain function-oriented Define operator
N
With attributes Questions help various do X: A: behave an to the any

Inheritance. virtual ambiguity private proctected attributes the restore appropriate why of various
and definition two in a types properties case program like virtual base object-oriented

T
advantages Y the types private { of of programs. in can’t //....}; class. B of

multi access base inheritances. example, inheritance. { in of of //....}; a be C++. attributes virtual
U
the Inheritance class. path of label inherited. inheritance.

following explain programs inheritance Explain base of How but an with class how State can
inheritance two ambiguities your are suitable without be ambiguities derived in answer a

W
inherited. more C++ remedy example. data syntax.Explain using

classes can with maintainable for can Explain be member example. virtual this differ? be
o
removed resolved problem base with in why and derived an class. by for

r
virtual example. reusable using so public that class? scope base attributes and
ld
compared Explain classes resolution

protected with of are


to a
Provided by JNTU World Team (www.alljntuworld.in)
63
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Chapter 4 Polymorphism and Virtual Functions Polymorphism For 4 3.14 “Good”
Polymorphism Function It parameters area Solution: #include float int void { } means one
name, multiple forms. example, the + (plus) operator in C++ will + 5 <-- integer addition
+ 2.0 <-- floating point addition
+ "Boy” <-- string concatenation
is of two types:
(i) Compile time(Static) polymorphism ▪ In compile time polymorphism, during program
compilation.
▪ Example: Function overloading compile time polymorphism (ii) Runtime(Dynamic)
polymorphism(late ▪ In runtime polymorphism program execution.
▪ Example: Virtual function Program
J is area(int, main( area(int); the of int

cout cin>>r>>l>>b; cout<< cout<< a <iostream.h> process rectangle. Overloading

N 4.1 ) r, and int); << l, b; “Area “Area “Enter types Write by of of of which the
T
circle rectangle a parameters.

U
Value program a is ”<<area(r)<<endl; single of is r, ”<<area(l,b);

to l & function overload b: ”; behave all is can information used (static all binding different
W
perform and to information binding achieve operator or needed for

o
different dynamic or runtime different static needed overloading to call task,

binding) polymorphism. linking data to a function depending call types: or are a early
r ld
function used is known binding) upon to is

achieve known
during
no of
function area () to calculate area of circle and
float area(int a)
Provided by JNTU World Team (www.alljntuworld.in)
64
www.alljntuworld.in JNTU World
{
return (3.14*a*a); } int {

} Output: Enter 7 Area Area Ambiguity Suppose void void void { } Note: area(int,int) functions
J
Following Object In member 8 object-oriented area(int ▪ ▪ 6 area(int,int);

area(float,int); main() of of the Here, circle circle return area(10,10); area(10.0,10); void void
Above reference typedef enum void void Slicing we variables. Value could functions

N
a, in have the f(int f(int f(int); f(mon); and is is int days{mon,tue,wed}
(a*b);
Function two 153.86 48 accept of int b) second x); &x); area(float, two parameter r,
programming, If integer; cannot l functions a & functions: a base b: double,

T
area() Overloading be class int) and overloaded: cannot // // function but .

U
the Unambiguous Ambiguous a instance It's derived our other
because be compiler will overloaded takes is class not assigned function 10.0 function a

W
typically doesn't compile normal, is call, its when treated call, know

value and inherits error! call-by-value calls the will which as from only area(int, a its generate

o
double, a one base difference derived parameter. you int){ class not error
r
want class } by a is ambiguity float. to defining instance, that use. Either one

ld
additional between
member takes of our a
variables defined in the derived class cannot be copied, since the base class has no place to
store them. This is a natural and unavoidable consequence of assignment by value from derived
Provided by JNTU World Team (www.alljntuworld.in)
class objects. The 65
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
term object slicing is sometimes used to refer to this aspect of assignment by value to a base
class instance. Object Slicing occurs when object of a derived class is assigned to an losing
part of the information - some of it is “sliced" away. Example: class A {
int x; }; class B : public A {

int y; }; So an object of type B has two data members, x and y Then if we are writing B A
Then Function When member Solution: #include<iostream.h> class {

}; class { b; a
J Program = B D:public b; the a public: void { cout<<"I }

public: void base function information Overriding N show() show() 4.2 B


T
class am always Demonstration and in in base using b derived works

U
about show"<<endl; Virtual when member class of we

Function
function contain invoke y will be same overriding.
W
that lost function member in a. function, using base Downloaded

o
From JNTU World (http://www.alljntuworld.in) object this of code: a base
r ld
class, thereby

then the base version of pointer.


the
{ cout<<"I am in derived show"<<endl;
Provided by JNTU World Team (www.alljntuworld.in)
66
www.alljntuworld.in JNTU World

} }; void main() {

B b, *bp; D d; bp=&b; bp->show(); bp=&d; bp->show(); } Output: I am in base show I am in


base show
Note: Here the base version of A virtual function is a member class. To create a virtual
function, virtual. When a class containing function to fit its own needs. methods" philosophy that
underlies form of the interface to that implements specific method.
Program Solution: #include<iostream.h> class { }; class
J B D:public public:

virtual { cout<<"I } N 4.3 its void operation am Write show()


T
in base a program as show"<<endl; it B

Downloaded From JNTU World (http://www.alljntuworld.in) relates function function. function In a

U
precede to essence, virtual polymorphism. demonstrate

specifically show that Each function the virtual () is function's redefinition will declared to work
W
The is virtual functions the inherited, virtual derived as within

declaration function.
it of overrides implement function the a class. the base virtual derived in That class the within

o
the the function derived is, base and class the the "one class redefined base
r ld
redefinition redefines version by interface, with class a

of show ().
by a derived the keyword the virtual multiple defines the derived class creates a
{
Provided by JNTU World Team (www.alljntuworld.in)
public: 67
www.alljntuworld.in JNTU World

void show() { }; void {

} Output: I I Important A defined same when class). virtual. function Remember! When

class virtual Pure A virtual am am pure base J in in main() that virtual function

we a function function, Derived base derived virtual pointer This cout<<"I } B D bp=&b; bp-
N
>show(); bp=&d; bp->show(); virtual by in access b, d; has the a Tips!

show is *bp; derived function function inherited also derived show is function can version can
use am the present be called still this in function class. made derived is class. of be is general

T
a a in function inherited, the virtual overridden. virtual It both to using can
function show"<<endl; point form: function base function access overriding base

U
its to and virtual can any pointer only that is derived be number

itself the nature has because called (no members no used class, matters of is

W
definition by also derived function as making always a inherited.
which whether base within objects, in base the class are the function it This the version common

o
base points for it base cannot means another class of (having to class. to the

r
base access is that the overridden derived function To same class when base
ld
declare the or members class, class. name) a is derived

derived by a called pure the the If as a


Provided by JNTU World Team
virtual return-type function-name (parameter-list) = 0; 68
(www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
When a virtual function is made pure, any derived class must provide its own definition. If the
derived class fails to override the pure virtual function, a compile-time error will result. Hence
definition for pure virtual function must be there in the derived class.
Abstract Classes A class that contains at least one pure virtual function is said to be abstract.
contains one or more functions for which there is no definition (that is, a objects of an abstract
class may be created. Instead, an abstract class constitutes an incomplete type that is used as
classes. Although we cannot create objects of an abstract class, we can create to an abstract
class. This base-class pointers and Program 4.4 Create find_vol() and a protected above
class named as respectively. Implement display the result. Solution: #include<iostream.h>
class Shape {
protected: double volume; public: virtual void find_vol()=0; }; class {
}; class {
J Cube: Sphere: protected: double public: Cube(); void protected:

N public find_vol(); public side;

Shape

Shape
T
Downloaded From JNTU World (http://www.alljntuworld.in) references Cube an

U
allows dynamic abstract attribute and abstract to Sphere

polymorphism select class named classes called having the as proper to volume. Shape
W
double support to virtual find which Create type out run-time

function.

o
contains volume attribute two polymorphism, new of a pure named a
r
derived pure Because a pointers foundation virtual virtual as which classes an

ld
side function and abstract function), for and

relies references from derived radius called upon class


the no
cube and a sphere. Also [BPUT 2010]
double radius; public:
Provided by JNTU World Team (www.alljntuworld.in)
69
www.alljntuworld.in JNTU World

Sphere(); void find_vol(); }; Cube::Cube() { cout<<”Enter side of the Cube:”<<endl; cin>>side;

} Sphere::Sphere () { cout<<”Enter radius of the sphere:”<<endl; cin>>radius; } void Cube::

find_vol() { volume=side*side*side; cout<<”Volume of Cube is: ”<<volume<<endl; } void {

volume=(4/3)*3.14*radius*radius*radius; cout<<”Volume } void {

J
} Output: Enter 3 Sphere:: main() side Shape Cube Sphere ptr=&cube; ptr-
N
>find_vol(); ptr=&sphere; ptr->find_vol(); of the find_vol() cube; *ptr;

T
sphere; of Cube: sphere is: ”<<volume;
U

World
Provided by JNTU World Team (www.alljntuworld.in)
Enter radius of the sphere: 4 70
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Volume of Cube is: 27 Volume of sphere is: 200.96

NTU
J
World
71 Provided by JNTU World Team
(www.alljntuworld.in)

Downloaded From JNTU World


(http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Assignment 4
Short Type Questions

Long J 1. 2. 3. 4. 5. 6. 7. 8. 9. 1. 2. 3. 4. 5. 6. 7. 8. Type Why Define Define Give

What Define Define How How Explain Explain overloading. Discuss “Pure Comment An Explain

N
Distinguish Explain Create appropriate implement input. Questions
abstract two class run compile is virtual function ambiguity early pure virtual your function object
run a function time example is on class function between time virtual called binding answer code
class functions time this polymorphism function slicing overriding overloading

T
called polymorphism? overloading statement. in of an polymorphism to

cannot function. function using and overloading static virtual with ADT? create force with

U
Volume late a a and have polymorphism. member suitable
suitable a overloading. the and can binding. objects suitable with function instances.
programmer be to function which can calculate an achieved? example. example. function be
named example. example. overloading. contains achieved? overriding What volume and as

W
to sphere redefine Also non-virtual then a with method of explain is

a and suitable sphere virtual the member cylinder called use ambiguity

o
function and examples. of find_vol cylinder having function. of the inside
r ld
problem abstract above based (). derived Write

in upon class function classes? class”.


down
user and
Provided by JNTU World Team (www.alljntuworld.in)
72
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Downloaded From JNTU World (http://www.alljntuworld.in)
Chapter 5 Operator Overloading
▪ It is most striking feature of C++.
▪ In operator overloading an operator can be operated on user defined data perform addition of
integers or real numbers. But we can overload this sum of two complex number.
▪ Only existing operators can be overloaded. New operators cannot be overloaded be
overloaded as it is not an operator.)
▪ It should obey the basic meaning of an operator i.e. + operator cannot be numbers.
▪ These operators The operator overloading (i) Member function (ii) Friend function
this Pointer Every object in C++ has this pointer is an implicit may be used to refer to Friend
functions do not member functions have Program 5.1 Write Solution: #include <iostream.h>
class Box {
J private: double double double public: Box(double { cout length

= l; h;
breadth height N <<"Constructor = = length; breadth; height;
T
b; l=2.0, access the have a cannot parameter a this can program invoking a

U
be pointer. to this be done its overloaded: pointer, to own object.

to by all demonstrate address member using:


W
because through functions. friends this an pointer. are important

o
Therefore, not members pointer inside of a called member a double b=2.0,

double h=2.0)

called." << endl;


r ld
operator used types. to i.e. (i.e. subtract to +

compute $ operator cannot


two
this pointer. The function, this
class. Only non static
}
Provided by JNTU World Team (www.alljntuworld.in)
73
www.alljntuworld.in JNTU World

double Volume() { return (length * breadth * height); } int compare(Box box) { return (this-

>Volume() > box.Volume()); }


}; void main(void) {
Box Box1(3.3, 1.2, 1.5); Box Box2(8.5, 6.0, 2.0);
if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout } }

Output: Constructor Constructor Box2 is equal Overloading A return_type { // } Often, valid


the overloading operations member J symbol. type(int, operator

N
operator operator called. called. << to Operators "Box2 or functions
T
larger function symbol(arg-list) is equal than return takes Box1 to or an this

U
larger object general than of Box1" form: the char, float, void

etc). When you create For example, if you are overloading a unary operator, arg-list will be
empty. <<endl;
World
class they operate on, but return_type can be any an operator function, substitute the
operator for the / operator, use operator/. When you are When you are overloading binary
Provided by JNTU World Team
operators, arg- list will contain one parameter. 74
(www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Operator Overloading Restrictions: There are some restrictions that apply to operator
overloading.
▪ ▪ ▪ ▪ ▪ ▪ Program Solution: #include<iostream.h> class A {
}; void A::getdata( {

} void A::operator {

} void {
} void {
J A::display( main() We We Except Finally, operator Except However,

base int public: void void void cout<<”Enter cin>>n;


n=n+1;

cout<<n; 5.2 N n; cannot cannot operator display( getdata( class) for for these

) ) ++( (:?), Write a the the it alter change derived ) chooses ); dot operators ); a ++( function =
T
number”; a operator, the operator program ); the class precedence relative

U
number call, cannot is operator (.) free to operator, and to

overload of be to itself. of asterisk operands overload overloaded: an functions operator


W
operator. unary operator any that are operator scope functions

operator an inherited (*). operator resolution ++ cannot (including by using takes.

o
any operator have member derived those default (::), overloaded class.
r
function. conditional arguments.

ld
by the

A a; a.getdata(); a++; a.display();


Provided by JNTU World Team (www.alljntuworld.in)
75
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

} Output: Enter 5 6
Solution: #include<iostream.h> class {
}; void {

} void {

} void {

} void { } Program
J A::getdata( A::display( main() A operator a number int

public: void friend void cout<<”Enter cin>>n;


x.n=x.n+1;
cout<<n;
A a.getdata(); a++; a.display();
a; 5.3

);
N n; display( getdata( void ++(A ) ) Write operator x) );

T U
a number”; a program ++( A &); to overload
Wo
unary operator ++ using friend function.

rld
Output: Enter a number
Provided by JNTU World Team (www.alljntuworld.in)
76
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World

56
Program 5.4 Write a program to overload numbers using member function.
Solution: #include<iostream.h> class Complex {
float real, img; public: Complex(float, float ); Complex operator + ( Complex); void display( ); };

Complex::Complex(float x, float y ) {
real=x; img=y } Complex Complex::operator { Complex temp.real=real+c.real;

temp.img=img+c.img; return(temp); } void {

} void {
J A::display( main( cout<<real<<” Complex c3=c1+c2; c1.display(

c2.display( N ))
temp;

TU
+j”<<img<<”\n”; +(Comlex c)

c1(2.5, 3.4), c2(4.2, 6.5), c3;


); );

W or
binary operator + to find sum of
ld
two complex

c3.display( ); }
Provided by JNTU World Team (www.alljntuworld.in)
77
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Output: 2.5+ j3.4 4.2+ j6.5 6.7+ j9.9
Note: As you can see, operator+ () has only one parameter even though operator. (You might
expect two parameters corresponding to the two The reason that operator+ () takes only one
parameter is that the operand passed implicitly to the function through the this pointer. The
operand parameter c. The fact that the left operand is passed using this also implies binary
operators are overloaded, it is the object on the left that generates function. The statement
c3=c1+c2; is same as c1.operator+(c2).
Program 5.5 Write a program to overload binary operator + numbers using friend
function.
Solution: #include<iostream.h> class Complex {
float real, img; public: Complex(float, friend Complex void display( ); }; Complex::Complex(float
{
} Complex {
J real=x; img=y

Complex temp.x=a.real+b.real; temp.y=a.img+b.img; return(temp); operator+(Comlex

N temp;
T
Downloaded From JNTU World (http://www.alljntuworld.in) float ); operator x, float

U
y+)( Complex, a, Complex b)

Complex);
W o
on operands it to overloads the the on one find

r
the call right important sum of left to is a the the side passed binary of binary
ld
operator two of point: operator.) the in +

+ is the
When
complex
} void A::display( )

78 Provided by JNTU World Team (www.alljntuworld.in)


www.alljntuworld.in JNTU World
{
cout<<real<<” +j”<<img<<”\n”; } void main() {

} Output: 2.5+ j3.4 4.2+ j6.5 6.7+ j9.9


Program program operator if(ob 1== cout<<”Objects else cout<<”Objects Solution:
#include<iostream.h> class X {
}; X::X(double { }
J Complex c1(2.5, 3.4), c2(4.2, 6.5), c3=c1+c2; c1.display();

c2.display(); c3.display();
5.5 Suppose there is a to create two objects named to perform the following operation ob
2)

double public: X(double, int void N operator==(X); display( x, double d1, are

are double); d2;


same”<<endl;
different”<<endl; );
TU
y) class ob c3;

1 called and within ob X 2 main():

W o
with of the two above double class type and
r ld
attributes. overload the [BPUT Write binary a

2010] C++ ==
d1=x; d2=y;

int X:: operator==(X p)


Provided by JNTU World Team (www.alljntuworld.in)
79
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
{
if(d1==p.d1 &&d2==p.d2) return 1; else return 0; } void main() {
X ob1(2.5, 3.4), ob2(2.5, 3.0); if(ob 1== ob 2) cout<<”Objects are same”<<endl; else
cout<<”Objects are different”<<endl; }
TU
JN
World
80 Provided by JNTU World Team (www.alljntuworld.in)
Downloaded From JNTU World (http://www.alljntuworld.in)

You might also like