0% found this document useful (0 votes)
7 views

Unit 2 Notes

Uploaded by

Anuj Samdariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit 2 Notes

Uploaded by

Anuj Samdariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 256

Object Oriented

Programming with C++

C++ Basics
Simple C++ Program
A Simple C++ Program
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

I iostream
will score good
is just like marks
we include stdio.hin
in c C++
program.
 It contains declarations for the identifier cout and the insertion
operator <<.
 iostream should be included at the beginning of all programs
that use input/output statements.

C++ Basics 3
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement
I like C++ so much
}
return 0;

I Awill score
namespace goodregion.
is a declarative marks in C++
 A namespace is a part of the program in which certain names are
recognized; outside of the namespace they’re unknown.
 namespace defines a scope for the identifies that are used in a
program.
 using and namespace are the keywords of C++.

C++ Basics 4
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

I will score good marks in C++


 std is the namespace where ANSI C++ standard class libraries are
defined.
 Various program components such as cout, cin, endl are
defined within std namespace.
 If we don’t use the using directive at top, we have to add the std
followed by :: in the program before identifier.
std::cout << “Hello World”;
C++ Basics 5
A Simple C++ Program (Cont…)
#include <iostream> //include header file
using namespace std;
int main()
{
cout << "Hello World"; // C++ statement

}
I like C++ so much
return 0;

I In
will scorereturns
C++, main() good marks
an integer in C++
type value.
 Therefore, every main() in C++ should end with a return 0;
statement; otherwise error will occur.
 The return value from the main() function is used by the
runtime library as the exit code for the process.

C++ Basics 6
Insertion Operator <<
cout << "Hello World";

 The operator << is called the


insertion operator.
 It inserts the contents of the
I like C++ so much
variable on its right to the object
on its left.
 The identifier cout is a predefined
I will score good marks in C++
object that represents standard
output stream in C++.
 Here, Screen represents the
output. We can also redirect the
output to other output devices. Output Using Insertion Operator
 The operator << is used as bitwise
left shift operator also.

C++ Basics 7
Program: Basic C++ program
Write a C++ Program to print following

Name: Gyan Ganga


City: Jabalpur
Country: India
I like C++ so much
I will score good marks in C++

C++ Basics 8
Program: Basic C++ program
#include <iostream>
using namespace std;
int main()
{

I like C++ so much


cout << " Name: Gyan Gnaga";
cout << " City: Jabalpur";
I will score good marks in C++
cout << " Country: India";
return 0;
}

Output
Name: Gyan Ganga City: Jabalpur Country: India
C++ Basics 9
Program: Basic C++ program(Cont…)
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
cout << "Name: GGITS"; cout << "Name: GGITS"<<endl;
cout << "City: Jabalpur\n"; cout << "City: Jabalpur"<<endl;
cout << "Country: India"<<endl;

}
I like C++ so much
cout << "Country: India";
return 0;
}
return 0;

I will score good


Output The endlmarks inandC++
manipulator \n has same
Name: GGITS effect. Both inserts new line to output.
City: Jabalpur
Country: India
 But, difference is endl immediate flush to the
output while \n do not.

C++ Basics 10
Extraction Operator >>
cin >> number1;
 The operator >> is called the
extraction operator.
 It extracts (or takes) the value Object Extraction Operator
from keyboard and assigns it to
I like C++ so much
cin >> number1
the variable on its right.
 The identifier cin is a predefined Variable

I object
will score good marks in C++
that represents standard
input stream in C++.
 Here, standard input stream KeyBoard
represents the Keyboard.
 The operator >> is used as
bitwise right shift operator also.

C++ Basics 11
Program: Basic C++ program
#include<iostream>
using namespace std;
int main()
{
int number1,number2;

cout<<"Enter First Number: ";


I like C++ so much
cin>>number1; //accept first number

I will score good marks in C++


cout<<"Enter Second Number: ";
cin>>number2; //accept first number

cout<<"Addition : ";
cout<<number1+number2; //Display Addition
return 0;
}

C++ Basics 12
C++ Tokens
C++ Tokens
 The smallest individual unit of a program is known as token.
 C++ has the following tokens:
− Keywords
#include <iostream>
− Identifiers using namespace std;
I like C++ so much
− Constants int main()
{
I will score good marks in C++
− Strings cout << "Hello World";
return 0;
− Special Symbols
}
− Operators

C++ Basics 14
Keywords and Identifier
 C++ reserves a set of 84 words for its own use.
 These words are called keywords (or reserved words), and each of
these keywords has a special meaning within the C++ language.
 Identifiers are names that are given to various user defined
I like C++ so much
program elements, such as variable, function and arrays.
 Some of Predefined identifiers are cout, cin, main
I will score good marks in C++
 We cannot use Keyword as user defined identifier.

C++ Basics 15
Keywords in C++
asm double new switch
auto else operator template
break enum private this
case extern protected throw
I like C++ so much
catch float public try
char for register typeof
I will score good marks in C++
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
C++ Basics 16
Rules for naming identifiers in C++
1. First Character must be an alphabet or underscore.
2. It can contain only letters(a..z A..Z), digits(0 to 9) or
underscore(_).
3. Identifier name cannot be keyword.
I4. like C++
Only first so much
31 characters are significant.

I will score good marks in C++

C++ Basics 17
Valid, Invalid Identifiers
1) Darshan Valid 12) xyz123 Valid
2) A Valid 13) part#2 Invalid
3) Age Valid 14) "char" Invalid
4) void Reserved word 15) #include Invalid
I like C++ so much16) This_is_a_ Valid
5) MAX-ENTRIES Invalid
Reserved word Valid
I7) time
will score
6) double
Valid
good marks
17) _xyz
18) 9xyz
in C++
Invalid
8) G Valid 19) main Standard identifier
9) Sue's Invalid 20) mutable Reserved word
10) return Reserved word 21) double Reserved word
11) cout Standard identifier 22) max?out Invalid
C++ Basics 18
Constants / Literals
 Constants in C++ refer to fixed values that do not change during
execution of program.

CONSTANTS

I like C++ so much


I will score
NUMERIC CHARACTER
CONSTANTS good marks in C++
CONSTANTS

SINGLE
INTEGER REAL STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS
CONSTANTS
i.e. i.e. i.e.
i.e.
123,-321, 6543 0.0083, -0.75 “Hello”, “197”
‘5’, ‘X’, ‘;’
C++ Basics 19
C++ Operators
C++ Operators
 All C language operators are valid in C++.
1. Arithmetic operators (+, - , *, /, %)
2. Relational operators (<, <=, >, >=, ==, !=)
3. Logical operators (&&, ||, !)

I like C++ so much


4.
5.
Assignment operators (+=, -=, *=, /=)
Increment and decrement operators (++, --)
I will score good marks in C++
6. Conditional operators (?:)
7. Bitwise operators (&, |, ^, <<, >>)
8. Special operators ()

C++ Basics 21
Arithmetic Operators

Operator example Meaning


+ a+b Addition

I like C++ so much


- Subtraction
a–b
* Multiplication
a*b
I will score goodDivision
/
marks in C++
a/b
% a%b Modulo division- remainder

C++ Basics 22
Relational Operators

Operator Meaning
< Is less than
<= Is less than or equal to
I like C++ so much
> Is greater than
I will score>= good marks
Is greater than orin C++
equal to
== Equal to
!= Not equal to

C++ Basics 23
Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
I like aC++ sobmucha && b a || b
true true true true
I willtruescore false
good marks
false intrueC++
false true false true
false false false false

 a && b : returns false if any of the expression is false


 a || b : returns true if any of the expression is true

C++ Basics 24
Assignment operator
 We assign a value to a variable using the basic assignment
operator (=).
 Assignment operator stores a value in memory.
 The syntax is
I like C++leftSide
so much= rightSide ;

I will score good marks in C++


It is either a literal |
Always it is a
a variable identifier |
variable identifier.
an expression.

Literal: ex. i = 1;
Variable identifier: ex. start = i;
Expression: ex. sum = first + second;
C++ Basics 25
Assignment Operators (Shorthand)
Syntax:
leftSide Op= rightSide ;

It is an arithmetic
operator.
IEx:like C++ so much
Simple assignment
Shorthand operator
x=x+3; operator
I willx+=3;score good marks
a = a+1
in C++a += 1
a = a-1 a -= 1
a = a * (m+n) a *= m+n
a = a / (m+n) a /= m+n
a = a % b a %= b
C++ Basics 26
Increment and Decrement Operators
 Increment ++
The ++ operator used to increase the value of the variable by one
 Decrement ─ ─
The ─ ─ operator used to decrease the value of the variable by one
Example:
I like x=100;
C++
x++;
so much
IAfter
will scorethegood
the execution value of x marks
will be 101. in C++
Example:
x=100;
x--;
After the execution the value of x will be 99.

C++ Basics 27
Pre & Post Increment operator
Operator Description
Pre increment operator (++x) value of x is incremented before assigning
it to the variable on the left

x = 10 ; After execution

I like C++ so much


p = ++x;
First increment value of
x by one
x will be 11
p will be 11

I will score goodDescription


Operator marks in C++
Post increment operator (x++) value of x is incremented after assigning it
to the variable on the left

x = 10 ; After execution
p = x++; x will be 11
p will be 10
First assign value of x

C++ Basics 28
What is the output of this program?
#include <iostream>
using namespace std;
int main ()
{
int x, y;
x = 5;
y = ++x * ++x;
cout << x << y;
I like C++ so much
x = 5;
y = x++ * ++x;
I will score good marks in C++
}
cout << x << y;

(A) 749735
(B) 736749
(C) 367497
(D) none of the mentioned

C++ Basics 29
Conditional Operator
Syntax:
exp1 ? exp2 : exp3
Working of the ? Operator:
 exp1 is evaluated first
I •like C++ so much
if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
• If exp1 is false(zero) then
I will score
- exp3 good
is evaluated marks
and its value invalueC++
becomes the of the expression
Ex: Ex:
m=2; m=2;
n=3; n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Value of r will be 3 Value of r will be 2
C++ Basics 30
Bitwise Operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
I like C++ so much
<< Shift left
>> Shift right
I will score good marks in C++

C++ Basics 31
Bitwise Operator Examples
8 = 1000 (In Binary)
6 = 0110 (In Binary)
Bitwise & (AND) Bitwise | (OR)
int a=8,b=6,c; int a=8,b=6,c;
c = a & b; c = a | b;
I like C++ so much
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 0 Output = 14
I will
Bitwise score
<< (Shift Left) good marks in Right)
Bitwise >> (Shift C++
int a=8,b=6,c; int a=8,b=6,c;
c = a << 1; c = a >> 1;
cout<<"Output ="<< c; cout<<"Output ="<< c;
Output = 16 Output = 4
left shifting is the equivalent of right shifting is the equivalent
multiplying a by a power of two of dividing a by a power of two

C++ Basics 32
New Operators in C++
It allows to access to the global
version of variable
:: Scope Resolution Declares a pointer to a member of
a class
::* Pointer-to-member declarator
->* Pointer-to-member operator To access pointer to class members

I .*likePointer-to-member
C++ so much operator To access pointer to data members
of class
Inew
willMemory
score good
allocation operatormarks in C++
Allocates memory at run time
delete Memory release operator
endl Line feed operator Deallocates memory at run time

setw Field width operator It is a manipulator causes a linefeed


to be inserted
It is a manipulator specifies a field
width for printing value
C++ Basics 33
Scope Resolution
Operator
Scope Resolution Operator(::)
....
....
Declaration of x in inner block hides
{ declaration of same variable declared in an
int x=10; outer block.
....
.... Therefore, in this code both variable x
refers to different data.
I like C++ so much
{
int x=1; Block-1
.... Block-2
I will score good
}
.... marks
 In C language, valuein
of xC++
declared in Block-1
is not accessible in Block-2.
....
 In C++, using scope resolution operator (::),
}
value of x declared in Block-1 can be
accessed in Block-2.

C++ Basics 35
#include <iostream>
Scope resolution example
using namespace std;
int m=10; Global declaration of variable m
int main()
{
int m=20; variable m declared , local to main
{
int k=m;
int m=3;
cout<<"we are in inner block\n";
cout<<"k="<<k<<endl; variable m
cout<<"m="<<m<<endl; declared again local to inner block
cout<<"::m="<<::m<<endl;
} Output:
cout<<"we are in outer block\n"; we are in inner block
cout<<"m="<<m<<endl; k=20
cout<<"::m="<<::m<<endl; m=3
return 0; ::m=10
} we are in outer block
m=20
::m=10
C++ Data Types
Basic Data types
C++ datatypes

User-defined Built-in Derived


I like C++ so much
structure
union
array
function
I will score good marks in C++
class
enumeration
pointer
reference

Integral Void Floating

int char float double

C++ Basics 38
Built in Data types
Data Type Size (bytes) Range
char 1 -128 to 127
unsigned char 1 0 to 255
short or int 2 -32,768 to 32,767
Iunsigned
like intC++ so much
2 0 to 65535
I will score good
long 4 marks
-2147483648in C++
to 2147483647
unsigned long 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+308
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932
C++ Basics 39
Type Conversion
Type Conversion
 Type Conversion is the process of converting one predefined data
type into another data type.

Type Conversion
I like C++ so much
I will score good
Implicit
marks in
Explicit
C++
(Automatically converts (Forcefully converts one
one datatype to another datatype to another
datatype) datatype)

 Explicit type conversion is also known as type casting.

C++ Basics 41
Type Conversion(Cont…)
int a;
double b=2.55;
a = b; // implicit type conversion

Icout
like<< C++ so much
a << endl; // this will print 2
a = int(b); //explicit type conversion
Icout
will<< score good marks in C++
a << endl; // this will print 2

C++ Basics 42
Implicit type conversion hierarchy

long
I like C++ so much float double double

long int
I will score intgood marks in C++
unsigned
int
char

C++ Basics 43
Implicit Type Conversion
#include <iostream>
using namespace std;
ans = count * avg
int main()
{ 5 10.01
int count = 5;
I like C++ so much
float avg = 10.01;
double ans;
double int float

I will score good


ans = count * avg;
marks
5.0 in C++ *
float
50.05
cout<<"Answer=:"<<ans; 50.05
return 0; float
double
}
Output:
Answer = 50.05
C++ Basics 44
Type Casting
 In C++ explicit type conversion is called type casting
 Syntax
type-name (expression) //C++ notation
 Example
I like average
C++ so much i; //C notation
= sum/(float)

I will average
score= good marks in C++
sum/float (i); //C++ notation

C++ Basics 45
#include <iostream>
using namespace std;
int main()
Type Casting Example
{
int a, b, c;
a = 19.99 + 11.99; //adds the values as float
// then converts the result to int
b = (int) 19.99 + (int) 11.99; // old C syntax
c = int (19.99) + int (11.99); // new C++ syntax

cout << "a = " << a << ", b = " << b;


cout << ", c = " << c << endl;

char ch = 'Z';
cout << "The code for " << ch << " is "; //print as char
cout << int(ch) << endl; //print as int
return 0;
}
Output:
a = 31, b = 30, c = 30
The code for Z is 90
Reference Variable
Reference Variable
 A reference provides an alias or a different name for a variable.
 One of the most important uses for references is in passing
arguments to functions.
declares variable a
int a=5;
I like C++ so much OUTPUT
int &ans = a; declares ans as reference to a
Its necessary to
Icout<<"a="<<a<<endl;
will score good
cout<<"&a="<<&a<<endl;
marks
a=5 in C++
initialize the
&a=0x6ffe34 Reference at the
time of declaration
cout<<"ans="<<ans<<endl; ans=5
cout<<"&ans="<<&ans<<endl; &ans=0x6ffe34
ans++;
cout<<"a="<<a<<endl; a=6
cout<<"ans="<<ans<<endl; ans=6

C++ Basics 48
Reference Variable(Cont…)
 C++ references allow you to create a second name for the a
variable.
 Reference variable for the purpose of accessing and modifying the
value of the original variable even if the second name (the
I like C++ so much
reference) is located within a different scope.

I will score good marks in C++

C++ Basics 49
Reference Vs Pointer
References Pointers
int i; int *p = &i;
int &r = i;

I like C++ so much p


addr
I will score good marks in C++
r i
addr
 A reference is a  A pointer is a variable
variable which refers which stores the address
to another variable. of another variable.

C++ Basics 50
Enumeration
Enumeration (A user defined Data Type)
 An enumeration is set of named integer constants.
 Enumerations are defined much like structures.

enum days{Sun,Mon,Tues,Wed,Thur,Fri,Sat};
0 1 2 3 4 5 6
I like C++
Keyword
Tag
so much
I will name
score Integer
good marks in C++
Values for symbolic constants

 Above statement creates days the name of datatype.


 By default, enumerators are assigned integer values starting with 0.
 It establishes Sun, Mon… and so on as symbolic constants for
the integer values 0-6.

C++ Basics 52
Enumeration Behaviour(Cont…)
enum coin { penny, nickel, dime, quarter=100,
half_dollar, dollar};

The values of these symbols are


penny 0
I like C++ so much
nickel
dime
1
2
I will score good marks in C++
quarter
half_dollar 101
100

dollar 102

C++ Basics 53
Enumeration Behaviour
enum days{ sun, mon, tue, wed, thu, fri, sat };
days today; variable today declared of type days

today = tue; Valid, because tue is an enumerator. Value 2 will


be assigned in today
today = 6; Invalid, because 6 is not an enumerator

today++; Invalid, today is of type days. We can not apply


++ to structure variable also
today = mon + fri; Invalid
Valid, days data type converted to int,
int num = sat;
value 6 will be assigned to num
num = 5 + mon; Valid, mon converted to int with value 1
Control Structures
Control Structures
 The if statement:
• Simple if statement
• if…else statement
• else…if ladder
I like C++nested
• if…else so much
I will score good marks in C++
The switch statement :
 The do-while statement: An exit controlled loop
 The while Statement: An entry controlled loop
 The for statement: An entry controlled loop

C++ Basics 56
Thank You
Object Oriented
Programming with C++

C++ Functions
C++ Functions
C++ Function
 A function is a group of statements that together perform a task.
 Functions are made for code reusability and for saving time and
space.
Function

I like C++ so much


Library Function User Defined Function
I like Rupesh sir
Predefined Created by User
Declarations inside header files Programmer need to declare it
Eg. printf() – stdio.h Eg. factorial()
pow() – cmath.h areaofcircle()
strcmp() – cstring.h

C++ Functions 3
C++ Function – (Cont…)
 There are three elements of user defined function

void func1(); Function Declaration


void main()
{
....
func1();I like C++ soFunction
much call
}
I like Rupesh sir
void func1()
{
.... Function
Function
definition
.... body
}

C++ Functions 4
Simple Function – (Cont…)
 Function Declaration
Syntax:
return-type function-name (arg-1, arg 2, …);
Example: int addition(int , int );

 Function Definition
Syntax:
return-type function-name (arg-1, arg 2, …)
{
... Function body
}
Example: int addition(int x, int y)
{
return x+y;
}
Categories of Function
(1) Function with arguments and returns value
Function arguments/
parameters

Return type int func1(int , int ); \\declaration


void main()

Function func1
I like C++ so much
{
....
I like Rupesh sir
returns integer value
to variable z
int z = func1(5,6); \\function call
}
int func1(int a, int b) \\definition
{
....
return a+b;
} returns a+b to calling function
C++ Functions 6
Categories of Function (Cont…)
(2) Function with arguments but no return value

void func1(int , int ); \\function declaration


void main()
{
.... I like C++ so much
func1(5,6); \\function call
} I like Rupesh sir
void func1(int a, int b) \\function definition
{
....
....
}

C++ Functions 7
Categories of Function (Cont..)
(3) Function with no argument but returns value

int func1();
void main()
{
....
I like C++ so much
int z = func1();
}
I like Rupesh sir
int func1()
{
....
return 99;
}

C++ Functions 8
Categories of Function (Cont…)
(4) Function with no argument and no return value
void func1();
void main()
{
....
I like C++ so much
func1();
}
I like Rupesh sir
void func1()
{
....
....
}

C++ Functions 9
Program: Categories of function
 Write C++ programs to demonstrate various categories of
function, Create function addition for all categories.

I like C++ so much


I like Rupesh sir

C++ Functions 10
Function with argument and returns value
#include <iostream> Value of
using namespace std; int main() Argument int fun1(int f)
{ {
..... .....
int add(int, int); b = fun1(a); .....
..... return e;
int main(){
I like C++ so much
int a=5,b=6,ans;
} Function
Result
}

I like Rupesh sir


ans = add(a,b);
cout<<"Addition is="<<ans;
return 0;
}
int add(int x,int y)
{
return x+y;
}
C++ Functions 11
Function with arguments but no return value
#include <iostream>
Value of
using namespace std; int main() Argument void fun1(int f)
{ {
..... .....
void add(int, int); fun1(a); .....
int main() ..... .....
{ I like C++ so much
} No Return
value
}
int a=5,b=6;
add(a,b); I like Rupesh sir
return 0;
}
void add(int x,int y)
{
cout<<"Addition is="<<x+y;
}
C++ Functions 12
Function with no argument but returns value

int add(); No
int main() Input int fun1()
{ {
int main() ..... .....
{ b = fun1(); .....
..... return e;
int ans;
ans = add();
I like C++ so much
} Function
Result
}

I like Rupesh sir


cout<<"Addition is="<<ans;
return 0;
}
void add()
{
int a=5,b=6;
return a+b;
}
C++ Functions 13
Function with no argument and no return value
void add();
No
int main() Input void fun1()
int main() { {
{ ..... .....
fun1(); .....
add(); ..... .....
return 0; I like C++ so much
} No Return }
} value
void add() I like Rupesh sir
{
int a=5,b=6;
cout<<"Addition is="<<a+b;
}

C++ Functions 14
Categories of Functions Summary
(1) Function with argument and returns value
Value of
int main() Argument int fun1(int f)
{ {
..... .....
b = fun1(a); .....

}I like C++ so much


.....
Function
Result
}
return e;

I like
(2) Function with Rupesh
argument sir value
and but no return
Value of
int main() Argument void fun1(int f)
{ {
..... .....
fun1(a); .....
..... .....
} No Return }
value

C++ Functions 15
Categories of Functions Summary
(3) Function with no argument and returns value
No
int main() Input int fun1()
{ {
..... .....
b = fun1(); .....

I like C++ so much


}
.....
Function
Result
}
return e;

I like
(4) Function with Rupesh
no argument sir
and but no return value
No
int main() Input void fun1()
{ {
..... .....
fun1(); .....
..... .....
} No Return }
value
C++ Functions 16
Call by Reference
Call by reference
 The call by reference method of passing arguments to a function
copies the reference of an argument into the formal parameter.
 Inside the function body, the reference is used to access the actual
argument used in the call.
Actual Parameters
I like C++ so much int main(){
add(a,b);
I like Rupesh sir } Formal Parameters

void add(int x,int y){


cout << x+y;
Note: }
 Actual parameters are parameters as they appear in function calls.
 Formal parameters are parameters as they appear in function
declarations / definition.
C++ Functions 18
Program: Swap using pointer, reference
 Write a C++ program that to swap two values using function
1. With pass by pointer
2. With pass by reference

I like C++ so much


I like Rupesh sir

C++ Functions 19
Program: Solution
void swapptr(int *x, int *y)
{
int z = *x;  Pointers as arguments
*x=*y;
*y=z;  References as
arguments
} I like C++ so much
void swapref(int &x, int &y)
{
int z = x;
I like Rupesh sir
int main()
x = y; {
y = z; ...
} swapptr(&a,&b);
swapref(a,b);
...
}
C++ Functions 20
Program: Solution
void swapptr(int *, int *);
void swapref(int &, int &);
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swapptr(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swapref(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
Program: Solution (Cont…)
void swapptr(int *x, int *y)
{
int z = *x;
*x=*y;
*y=z;
} I like C++ so much
void swapref(int &x, int &y)
{ I likeOUTPUT
Rupesh sir
int z = x;
Before Swap
x = y;
a=45 b=35
y = z;
After Swap with pass by pointer
}
a=35 b=45
After Swap with pass by reference
a=45 b=35
C++ Functions 22
Program: Return by Reference
 Write a C++ program to return reference of maximum of two
numbers from function max.

I like C++ so much


I like Rupesh sir

C++ Functions 23
Program: Solution
int& max(int &, int &);
int main()  Function declaration
{ returning reference
int a=5,b=6,ans;
ans = max(a,b);
I like C++ so much
cout<<"Maximum="<<ans;
}
I like Rupesh sir
int& max(int &x,int &y)
{
if (x>y)
return x;
else
return y;
}
C++ Functions 24
Program: Returning Reference
int x;  setx() is declared with a
int& setdata(); reference type,
int main() int&
as the return type:
{  int& setx();
setdata() = 56;
I like C++ so much
cout<<"Value="<<x;
This function contains
return x;
return 0; I like Rupesh sir
 You can put a call to this function
on the left side of the equal sign:
}
int& setdata() setx() = 92;
 The result is that the variable
{ returned by the function is
return x; assigned the value on the right
} side of the equal sign.

C++ Functions 25
C Preprocessors
Macros
C Preprocessors Macros
 C Preprocessor is a text substitution in program.
 It instructs the compiler to do pre-processing before the actual
compilation.
 All preprocessor commands begin with a hash symbol (#).

I like C++ so much


I like Rupesh sir

C++ Functions 27
C Preprocessor Macro Example
#include <stdio.h>
#define PI 3.1415
Preprocessor
#define circleArea(r) (PI*r*r)
int main()
{
int radius;
float area;
I like C++ so much
I like Rupesh sir
printf("Enter the radius: ");
scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %f", area);
return 0;  Every time the program encounters
} circleArea(argument), it is replaced by
(3.1415*(argument)*(argument)).
C++ Functions 28
Inline Functions
Inline Functions
 Every time a function is called it takes a lot of extra time to
execute series of instructions such as
1. Jumping to the function
2. Saving registers

I like C++ so much


3. Pushing arguments into stack
4. Returning to the calling function
I like Rupesh sir
 If a function body is small then overhead time is more than actual
code execution time so it becomes more time consuming.
 Preprocessor macros is a solution to the problem of small
functions in C.
 In C++, inline function is used to reduce the function call
overhead.

C++ Functions 30
Inline Functions (Cont…)
Syntax:
inline return-type function-name(parameters)
{
// function code
}

I like C++ so much


 Add inline word before the function definition to convert simple
function to inline function.
Example: I like Rupesh sir
inline int Max(int x, int y)
{
if (x>y)
return x;
else
return y;
}
C++ Functions 31
Program: Inline function
 Write a C++ program to create inline function that returns cube of
given number (i.e n=3, cube=(n*n*n)=27).

I like C++ so much


I like Rupesh sir

C++ Functions 32
Program: Solution
#include <iostream>
using namespace std;

inline int cube(int s)


{
I like C++ so much
return s*s*s;
}
int main() I like Rupesh sir
{
cout << "The cube of 3 is: " << cube(3);
return 0;
}
 Calls inline function cube with argument 3
C++ Functions 33
Critical situations Inline Functions
 Some of the situations inline expansion may not work
1) If a loop, a switch or a goto exists in function body.
2) If function is not returning any value.
3) If function contains static variables.
I like C++ so much
4) If function is recursive.

I like Rupesh sir

C++ Functions 34
Function Overloading
Function Overloading
 Suppose we want to make functions that add 2 values, add 3
values , add 4 values
In C Function with
int sum(int a, int b); same name in a
I like C++ so much
int sum(int a, int b, int c);
int sum(int a, int b, int c, int d);
program is not
allowed in C
I like Rupesh sir language

In C++ Function with


int sum(int a, int b); same name in a
int sum(int a, int b, int c); program is
int sum(int a, int b, int c, int d); allowed in C++
language
C++ Functions 36
Function overloading – Cont…
 C++ provides function overloading which allows to use multiple
functions sharing the same name .
 Function overloading is also known as Function Polymorphism in
OOP.
 It is the practice of declaring the same function with different
signatures. I like C++ so much
 However, theI two
like Rupesh
functions sir name must differ in at
with the same
least one of the following, Arguments
a) The number of arguments make the
b) The data type of arguments function
c) The order of appearance of arguments unique

 Function overloading does not depends on return type.

C++ Functions 37
Function Overloading
int sum(int a, int b); Valid

float sum(int a, int b); Invalid

int sum(int a, int c); Invalid


I like C++ so much
int sum(int a, float b); Valid
I like
int sum(float Rupesh
b, int a); sir Valid

float sum(float a, float b); Valid

int sum(int a, int b, int c); Valid

int sum(int a, float b, int c); Valid

C++ Functions 38
Program: Function overloading
 Write a C++ program to demonstrate function overloading. Create
function display() with different arguments but same name

I like C++ so much


I like Rupesh sir

C++ Functions 39
Program: Solution (Cont…)
void display(int var)
{
cout << "Integer number: " << var << endl;
}
I like C++ so much
void display(float var)
{

} I like Rupesh sir


cout << "Float number: " << var << endl;

void display(int var1, float var2) {


cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}

C++ Functions 40
Program: Solution
int main()
{
int a = 5; float b = 5.5;
display(a);
display(b);
I like C++ so much
display(a, b);
return 0;
} I like Rupesh sir

C++ Functions 41
Program: Function overloading
 Write a C++ program to demonstrate function overloading. Create
function area() that calculates area of circle, triangle and box.

I like C++ so much


I like Rupesh sir

C++ Functions 42
float area(int r)
{
Program #7
return 3.14*r*r; Solution
}
float area(int h, int b)
{
return 0.5*h*b;
}
I like C++ so much
float area(int l, int w, int h)
{
I like Rupesh sir
return l*w*h;
}
int main(){
cout<<"area of circle="<<area(5);
cout<<“\n area of triangle="<<area(4,9);
cout<<“\n area of box="<<area(5,8,2);
return 0;
}
C++ Functions 43
Default Function
Arguments
Default Function Argument

I like C++ so much


int cubevolume(int l=5, int w=6, int h=7)
{
return l*w*h;
} I like Rupesh sir
int main() Here, there can be
If argument fourspecified
is not types ofthen,
function
{ compiler lookscalls possible to see how
at declaration
cubevolume(); many arguments a function uses and
cubevolume(9);
alert program to use default values
cubevolume(15,12);
cubevolume(3,4,7);
}
C++ Functions 45
Default Argument Example
int volume(int l=5,int w=6, int h=7)
{
return l*w*h;
}
int main() {
I like C++ so much
cout<<"volume="<<volume()<<endl;
cout<<"volume="<<volume(9)<<endl;
I like Rupesh sir
cout<<"volume="<<volume(15,2)<<endl;
cout<<"volume="<<volume(3,4,7)<<endl;
return 0;
}
 Function call passing
withoutall
only
passing
two oneargument.
argument.
arguments.
arguments.
 Explicitly
Default value
value5,6,7
9 passed
3,4,7
15,2 considered
to l.totol,w
passed
passed for l,
l,w,h h respectively.
respectively.
respectively.
w,
 Default value 6,7 considered
7 considered for for respectively.
respectively.
h w,h
C++ Functions 46
Default Arguments
 while invoking a function If the argument/s are not passed then,
the default values are used.
 We must add default arguments from right to left.
 We cannot provide a default value to a particular argument in the
I like C++ so much
middle of an argument list.
 Default arguments are useful in situations where some arguments
always have Ithelike Rupesh sir
same value.

int cubevolume( int l = 2, int w = 2, int h = 2 )


{
return l*w*h;
}
C++ Functions 47
Default Arguments (Cont…)
 Legal and illegal default arguments
void f(int a, int b, int c=0); Valid
void f(int a, int b=0, int c=0); Valid
void f(int a=0, int b, int c=0); Invalid
I like C++ so much
void f(int a=0, int b, int c); Invalid
void f(int a=0, int b=0, int c=0); Valid
I like Rupesh sir

C++ Functions 48
Common Mistakes
(1) void add(int a, int b = 3, int c, int d = 4);

 You cannot miss a default argument in between two arguments.


 In this case, c should also be assigned a default value.

I like C++ so much


(2) void add(int a, int b = 3, int c, int d);
I like Rupesh sir
 If you want a single default argument, make sure the argument is
the last one.

C++ Functions 49
Program: Default Arguments
 Write a C++ program to create function sum(), that performs
addition of 3 integers also demonstrate Default Arguments
concept.

I like C++ so much


I like Rupesh sir

C++ Functions 50
Program: Default Arguments
#include <iostream>
using namespace std;
int sum(int x, int y=10, int z=20)
{
return (x+y+z);
} I like C++ so much
int main()
{ I like Rupesh sir
cout << "Sum is : " << sum(5) << endl;
cout << "Sum is : " << sum(5,15) << endl;
cout << "Sum is : " << sum(5,15,25) << endl;
return 0;
}

C++ Functions 51
Thank You
Object Oriented
Programming with C++

Objects &
Classes
Outline Weightage: 15%

 Basics of Object and Class in C++


 Private and Public Members
 Static data and Function Members
 Constructors and their types
 Destructors I like C++ so much


I like
Operator Overloading
Type Conversion
Rupesh sir

Objects and Classes 2


Object and Class in C++
What is an Object?

Pen Board Laptop


I like C++ so much
I like Rupesh sir

Bench Projector Bike

Physical objects…
Objects and Classes 4
What is an Object? (Cont…)

I like C++ so much


I
Result
like Rupesh sir
Bank Account

Logical objects…

Objects and Classes 5


Attributes and Methods of an Object

Bank Account

Object: Person Object: Car Object: Account


I like C++ so much
Attributes Attributes Attributes
Name I like Rupesh
Company sir AccountNo
Age Color HolderName
Weight Fuel type AccountType
Methods Methods Methods
Eat Start Deposit
Sleep Drive Withdraw
Walk Stop Transfer
Objects and Classes 6
Class

A Class is a blueprint of an object


I like C++ so much
I like Rupesh sir
A Class describes the object

Objects and Classes 7


Class car

I like C++ so much


Class: Car
I like Rupesh sir

Objects and Classes 8


Class: Car

Properties (Describe)
Company Methods (Functions)
Model Start
Color Drive
Mfg. Year Park
Price On_break
Fuel Type On_lock
Mileage On_turn
Gear Type
Power Steering
Anti-Lock braking system
Objects of Class Car

Honda City Hyundai i20 Sumo Grand


I like C++ so much
I like Rupesh sir
Mercedes E class Swift Dzire

Objects and Classes 10


Class in C++
 A class is a blueprint or template that describes the object.
 A class specifies the attributes and methods of objects.

Example:
class car
{ I like C++ so much
// data members and member functions
}car1; I like Rupesh sir
 In above example class name is car, and car1 is object of that
class.

Objects and Classes 11


Specifying Class

How to declare / write class ?

I like C++ so much


How to create an object
I like Rupesh sirof class)?
(instance/variable

How to access class members ?

Objects and Classes 12


How to declare / write class ?

Class
class car
Car
{
private:
I like C++ so much
Attributes
int price;
I like Rupesh sirPrice
float mileage;
public: Mileage
void start(); Methods
void drive(); Start
}; Drive

Objects and Classes 13


How to create an object ?
Syntax:
className objectVariableName;

Class
class car I like C++ so much Object
{
private: I like Rupeshintsirmain()
int price;
{
float mileage;
public: car c1;
void start(); c1.start();
void drive(); }
};
Objects and Classes 14
Object in C++
 An object is an instance of a class
 An object is a variable of type class

Class Object
class car I like C++ so much
{ int main()
private: I like Rupesh{ sir
int price; car c1;
float mileage; c1.start();
public: c1.drive();
void start(); }
void drive();
};
Objects and Classes 15
Program: class, object
 Write a C++ program to create class Test having data members
mark and spi.
 Create member functions SetData() and DisplayData()to
demonstrate class and objects.
I like C++ so much
I like Rupesh sir

Objects and Classes 16


#include <iostream>
using namespace std;
Program: class, object
class Test
{ int main()
private: {
int mark; Test o1;
float spi; o1.SetData();
public: o1.DisplayData();
void SetData() return 0;
{ }
mark = 270;  Executes
Calling
Creates statements
Startingmember
point
an object ao1 and
offunction.
Program
of
spi = 6.5; return
type to
Control calling
jumps
Test tofunction
definition
}
of SetData()
DisplayData()
void DisplayData()
{
cout << "Mark= "<<mark<<endl;
cout << "spi= "<<spi;
}
} ;
class Test int main()
{ {
private: Test o1,o2;
int mark; o1.SetData();
float spi; o1.DisplayData();
public: o2.SetData();
void SetData() o2.DisplayData();
{ return 0;
cin>>mark; }
cin>>spi;
} mark = 50
void DisplayData() o1
{
cout << "Mark= "<<mark; spi = 7.5
cout << "spi= "<<spi;
} mark = 70
} ;
o2
spi = 6.83
Program: class, object
 Write a C++ program to create class Car having data members
Company and Top_Speed.
 Create member functions SetData() and DisplayData()
and create two objects of class Car.
I like C++ so much
I like Rupesh sir

Objects and Classes 19


class Car
{ Program: class, object
private: int main()
char company[20]; {
int top_speed; Car o1;
public: o1.SetData();
void SetData(){ o1.DisplayData();
cout<<"Enter Company:"; return 0;
cin>>company; }
cout<<"Enter top speed:";
cin>>top_speed;
}
void DisplayData()
{
cout << "\nCompany:"<<company;
cout << "\tTop Speed:"<<top_speed;
}
} ;
Program: class, object
 Write a C++ program to create class Employee having data
members Emp_Name, Salary, Age.
 Create member functions SetData() and DisplayData().
 Create two objects of class Employee
I like C++ so much
I like Rupesh sir

Objects and Classes 21


class Employee
{
Program: class, object
private:
char name[10];
int salary, age; int main()
{
public: Employee o1;
void SetData() o1.SetData();
{ o1.DisplayData();
cin>>name>>salary>>age; return 0;
} }
void DisplayData()
{
cout << “Name= "<<name<<endl;
cout << “salary= "<<salary<<endl;
cout << “age= "<<age;
}
} ;
Private and Public Members

Private Public
Private Members
 ByPrivate
defaultmembers of the class
all the members of can
classbe
Class accessed within the class and from
are private
member functions of the class.
 A private member variable or
class car
function cannot be accessed, or even
{ Private:
long int price;
I like C++ so muchviewed from outside the class.

float mileage;
void setdata()
I like Rupesh sir
This feature in OOP is known as Data
{ hiding / Encapsulation
price = 700000;
mileage = 18.5;
}
};

Objects and Classes 24


Private Members
 Private members of the class can be accessed within the class and
from member functions of the class.
 They cannot be accessed outside the class or from other
programs, not even from inherited class.
I like C++ so much
 If you try to access private data from outside of the class, compiler
throws error.
 I like
This feature in Rupesh
OOP is known sir / Encapsulation.
as Data hiding
 If any other access modifier is not specified then member default
acts as Private member.

Objects and Classes 25


Public Members
Class The public
Public members
members of a class from
are accessible can
class car beanywhere
accessed outside the class but
using
{ the objectwithin
nameaand dot operator '.'
program.
private:
I like C++ so much
long int price;
float mileage;
Object
public:
I like Rupesh sir
char model[10];
int main()
void setdata()
{
{
price = 700000; car c1;
mileage=18.53; c1.model = "petrol";
} c1.setdata();
}; }
Objects and Classes 26
Public Members
 The public keyword makes data and functions public.
 Public members of the class are accessible by any program from
anywhere.
 Class members that allow manipulating or accessing the class data
are made public. I like C++ so much
I like Rupesh sir

Objects and Classes 27


Data Hiding in Classes
CLASS
No entry to Private Area
Private area Data
X
Functions
I like C++ so much
Entry allowed to I like Rupesh sir
Public Area

Public area Data


Functions

Objects and Classes 28


Example Class in C++
class Test By Default the members of a
{ private is a Keyword
class are private.
private:
int data1; Private data and functions
float data2; can be written here
public:
I like C++ so much
void function1()
{
public is a
Keyword }
I like Rupesh sir
data1 = 2;

float function2() Public data and functions


{ can be written here
data2 = 3.5;
return data2;
}
};
Objects and Classes 29
Function Definition Outside Class
Function definition outside the class
Syntax:
Return-type class-name :: function-name(arguments)
{
Function body;
 The membership label class-name::
}
I like C++ so much
tells the compiler that the function
belongs to class
Example: I like Rupesh sir
void Test :: SetData(int i,int j)
{
mark = i;
spi = j;
}

Objects and Classes 31


Function Definition outside class
class car
{
private:
float mileage;
public:
float updatemileage();
void car :: setdata()
void setdata() ;
{
I like C++ so much
{
mileage = 18.5;
mileage = 18.5;
} I like Rupesh sir
}
};
int main()
{
float car :: updatemileage() car c1;
{ c1.setdata();
return mileage+2; c1.updatemileage();
}
}

Objects and Classes 32


class Test Program: function outside
{ class
private: int main()
int mark; {
float spi; Test o1;
public: o1.SetData(70,6.5);
void SetData(int,float); o1.DisplayData();
void DisplayData(); return 0;
}
};
void Test :: SetData(int i,float j){
mark = i;
spi = j;  The membership label Test::
} tells the compiler that the
void Test :: DisplayData() SetData() and
{ DisplayData() belongs to
cout << "Mark= "<<mark; Test class
cout << "\nspi= "<<spi;
}
Member Functions with
Arguments
Program: Function with argument
 Define class Time with members hour, minute and second.
Also define function to setTime() to initialize the members,
print() to display time. Demonstrate class Time for two
objects.

I like C++ so much


I like Rupesh sir

Objects and Classes 35


Program: Function with argument
#include<iostream>
using namespace std;
class Time
{
private :
I like C++ so much
int hour, minute, second;
public :
I like Rupesh sir
void setTime(int h, int m, int s);
void print();
};

Objects and Classes 36


Program: Function with argument
void Time::setTime(int h, int m, int s)
{
hour=h;
minute=m;
second=s;
} I like C++ so much
void Time::print()
{ I like Rupesh sir
cout<<"hours=\n"<<hour;
cout<<"minutes=\n"<<minute;
cout<<"seconds=\n"<<second;
}

Objects and Classes 37


Program: Function with argument
int main()
{
int h,m,s;
Time t1;
cout<<"Enter hours="; cin>>h;
I like C++ so much
cout<<"Enter minutes="; cin>>m;
cout<<"Enter seconds="; cin>>s;
I like Rupesh sir
t1.setTime(h,m,s);
t1.print();
return 0;
}

Objects and Classes 38


Program: Function with argument
 Define class Rectangle with members width and height.
Also define function to set_values() to initialize the
members, area() to calculate area. Demonstrate class
Rectangle for two objects.

I like C++ so much


I like Rupesh sir

Objects and Classes 39


class Rectangle
{ Program: Function
int width, height; with argument
public:
void set_values (int,int);
int area(){
return width*height;
}
};
void Rectangle::set_values (int x, int y){
width = x; height = y;
}
int main(){
Rectangle rect;
rect.set_values(3,4);
cout << "area: " << rect.area();
return 0;
}
Program: Function with argument
 Define class Employee with members age and salary.
1. Also define function to setdata() to initialize the members.
2. Define function displaydata() to display data.
3. Demonstrate class Employee for two objects.
int main(){ I like C++ so much
Employee yash,raj;
I like Rupesh sir
yash.setData(23,1500);
yash.displaydata();

raj.setData(27,1800);
raj. displaydata();
return 0;
}
Objects and Classes 41
Program: Function with
class Employee{ argument
private :
int age; int salary;
public :
void setData(int , int);
void displaydata();
}; I like C++ so much
void Employee::setData(int x, int y){
age=x; I like Rupesh sir
salary=y;
}
void Employee::displaydata(){
cout<<"age="<<age<<endl;
cout<<"salary="<<salary<<endl;
}
Objects and Classes 42
Passing Objects as Function
Arguments
Function with argument and returns value
#include <iostream> Value of
using namespace std; int main() Argument int fun1(int f)
{ {
..... .....
int add(int, int); b = fun1(a); .....
..... return e;
int main(){
int a=5,b=6,ans;
I like C++ so much
} Function
Result
}

ans = add(a,b);
I like Rupesh sir
cout<<"Addition is="<<ans;
return 0;
}
int add(int x,int y)
{
return x+y;
}
Objects and Classes 44
Object as Function arguments
time
int time
int
t1
a t2
b

Function
I like C++ so much
void add(intI x,
like Rupesh
int y) void sir
addtime(time x, time y)
{ {
statements… statements…
} }
int main() int main()
{ {
int a=5,b=6; time t1,t2,t3;
add(a,b); t3.addtime(t1,t2);
} }
Objects and Classes 45
Object as Function arguments

I like C++ so much


I like Rupesh sir

Objects and Classes 46


class Time
{
Program: passing object
int hour, minute, second; as argument
public :
void getTime(){
cout<<"\nEnter hours:";cin>>hour;
cout<<"Enter Minutes:";cin>>minute;
cout<<"Enter Seconds:";cin>>second;
}
void printTime(){
cout<<"\nhour:"<<hour;
cout<<"\tminute:"<<minute;
cout<<"\tsecond:"<<second;
}
void addTime(Time x, Time y){
hour = x.hour + y.hour;
minute = x.minute + y.minute;
second = x.second + y.second;
}
};
int main() Program: passing object
{ as argument
Time t1,t2,t3;

t1.getTime();
t1.printTime();

t2.getTime();
t2.printTime();

t3.addTime(t1,t2);
cout<<"\nafter adding two objects";
t3.printTime();

return 0;
}
t3.addTime(t1,t2);

Here, hour, minute and second represents data of object t3


because this function is called using code t3.addTime(t1,t2)

Function Declaration
void addTime(Time x, Time y)
{
hour = x.hour + y.hour;
minute = x.minute + y.minute;
second = x.second + y.second;
}
Program: Passing object as argument
 Define class Complex with members real and imaginary .
Also define function to setdata() to initialize the members,
print() to display values and addnumber() that adds two
complex objects.

I like C++ so much


 Demonstrate concept of passing object as argument.

I like Rupesh sir

Objects and Classes 50


Program: Passing object as int main()
argument {
class Complex Complex c1,c2,c3;
{ c1.readData();
private: c2.readData();
int real,imag; c3.addComplexNumbers(c1, c2);
public: c3.displaySum();
void readData() }
{
cout<<"Enter real and imaginary number:";
cin>>real>> imag;
}
void addComplexNumbers(Complex comp1, Complex comp2)
{
real=comp1.real+comp2.real;
imag=comp1.imag+comp2.imag;
}
void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
Passing and Returning Objects
Passing and returning object
time
int time
int
t1
a t2
b

Function result
I like C++ so much
int add(int I
x,like
int y)Rupesh sir
time addtime(time x, time y)
{ {
return return //object of class time
} }
int main() int main()
{ {
int a=5,b=6,result; time t1,t2,t3,result;
result = add(a,b); result = t3.addtime(t1,t2);
} }
Objects and Classes 53
Passing and returning object

I like C++ so much


I like Rupesh sir

Objects and Classes 54


Program: Passing and Returning an Object
 Define class Time with members hour, minute and second.
Also define function to getTime() to initialize the members,
printTime() to display time and addTime() to add two
time objects. Demonstrate class Time.

I like C++ so much


1. Passing object as argument
2. Returning object
I like Rupesh sir

Objects and Classes 55


class Time{ Program: Returning
int hour, minute, second;
public : object
void getTime(){
cout<<"\nEnter hours:";cin>>hour;
cout<<"Enter Minutes:";cin>>minute;
}
void printTime(){
cout<<"\nhour:"<<hour;
cout<<"\tminute:"<<minute;
}
Time addTime(Time t1, Time t2){
Time t4;
t4.hour = t1.hour + t2.hour;
t4.minute = t1.minute + t2.minute;
return t4;
}
};
Program: Returning
int main() object
{
Time t1,t2,t3,ans;

t1.getTime();
t1.printTime();

t2.getTime();
t2.printTime();

ans=t3.addTime(t1,t2);
cout<<"\nafter adding two objects";
ans.printTime();

return 0;
}
Program: Returning object
 C++ program to add two complex numbers by Pass and Return
Object from the Function.

I like C++ so much


I like Rupesh sir

Objects and Classes 58


class Complex
{
Program: Returning object
private:
int real,imag;
public:
void readData()
{
cout<<"Enter real and imaginary number:";
cin>>real>> imag;
}
Complex addComplexNumbers(Complex comp1, Complex comp2)
{
Complex temp;
temp.real=comp1.real+comp2.real;
temp.imag=comp1.imag+comp2.imag;
return temp;
}
void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
Program: Returning object
int main()
{
Complex c1,c2,c3,ans;
c1.readData();
c2.readData();
ans = c3.addComplexNumbers(c1, c2);
ans.displaySum();
}
Nesting Member Functions
Nesting Member functions
 A member function of a class can be called by an object of that
class using dot operator.
 A member function can be also called by another member
function of same class.
I like C++ so much
 This is known as nesting of member functions.

I like Rupesh sir


void set_values (int x, int y)
{
width = x;
height = y;

printdata();
}

Objects and Classes 62


Program: Nesting member function
 Define class Rectangle with member width,height. Also
define function to setvalue(), displayvalue().
Demonstrate nested member functions.

I like C++ so much


I like Rupesh sir

Objects and Classes 63


Program: Nesting member function
class rectangle{
int w,h;
public:
void setvalue(int ww,int hh)
{
w=ww;
h=hh;
I like C++ so much
int main(){
rectangle r1;
}
displayvalue();
I like Rupesh sir
r1.setvalue(5,6);
void displayvalue() r1.displayvalue();
{ return 0;
cout<<"width="<<w; }
cout<<"\t height="<<h;
}
};
Objects and Classes 64
Memory allocation of objects
 The member functions are created and placed in the memory
space only once at the time they are defined as part of a class
specification.
 No separate space is allocated for member functions when the
I like C++ so much
objects are created.
 Only space for member variable is allocated separately for each
I like
object because, Rupesh
the member sirwill hold different data
variables
values for different objects.

Objects and Classes 65


Memory allocation of objects(Cont…)
Common for all objects
Member function 1

Member function 2

I like C++ so much


Memory created when, Functions defined

Object 1 Object 2 Object 3


I like
Member variable 1 Rupesh
Member variable 1sir Member variable 1

Member variable 2 Member variable 2 Member variable 2

Memory created when Object created

Objects and Classes 66


class Account Object A1
{
Account No 101
int Account_no,Balance;
char Account_type[10]; Account Type Current
public: Balance 3400
void setdata(int an,char at[],int bal)
{
Object A2
Account_no = an;
Account_type = at; Account No 102
Balance = bal; Account Type Saving
}
}; Balance 150

Object A3
int main(){
Account A1,A2,A3; Account No 103
A1.setdata(101,“Current“,3400); Account Type Current
A2.setdata(102,“Saving“,150);
Balance 7900
A3.setdata(103,“Current“,7900);
return 0;
}
Static Data members / variables
Static Data members
A static data member is useful,
when all objects of the same class must share a common
information.

Just write static keyword prefix to regular variable

I like C++ so much


It is initialized to zero when first object of class created
I like Rupesh sir
Only one copy is created for each object

Its life time is entire program

Objects and Classes 69


class demo Static Data members
{
static int count;
public:
void getcount()
{ count
cout<<"count="<<++count;
} 0
3
1
2
};

int demo::count;
d1 d2 d3
int main()
{
demo d1,d2,d3;
d1.getcount(); Static members are declared inside
d2.getcount(); the class and defined outside the
d3.getcount(); class.
return 0;
}
class demo
Regular Data members
{
int count;

public:
void getcount()
{
count = 0; d1 d3
cout<<"count="<< ++count;
d2
}
};
int main() 10 01 10
{
demo d1,d2,d3; count count count
d1.getcount();
d2.getcount();
d3.getcount();
return 0;
}
Static Data Members
 Data members of the class which are shared by all objects are known as
static data members.
 Only one copy of a static variable is maintained by the class and it is
common for all objects.
 Static members are declared inside the class and defined outside the
class. I like C++ so much


I like Rupesh sir
It is initialized to zero when the first object of its class is created.
you cannot initialize a static member variable inside the class
declaration.
 It is visible only within the class but its lifetime is the entire program.
 Static members are generally used to maintain values common to the
entire class.

Objects and Classes 72


Program : Static data member
class item
{
int number;
static int count;// static variable declaration
public:
I like C++ so much
void getdata(int a){
number = a;

}
count++;
I like Rupesh sir
void getcount(){
cout<<"\nvalue of count: "<<count;
}
};
int item :: count; // static variable definition

Objects and Classes 73


Program : Static data member
int main()
{ Object a Object b Object c
item a,b,c; number number number
100 200 300
a.getdata(100);

I like C++ so muchcount


a.getcount();

I like Rupesh sir 1230


b.getdata(200);
a.getcount();

c.getdata(300);
a.getcount(); Output:
value of count: 1
return 0; value of count: 2
} value of count: 3

Objects and Classes 74


Program : Static data member
class shared { int main() {
static int a; shared x, y;
int b; x.set(1, 1);
public: x.show();
void set(int i, int j) {a=i; b=j;} y.set(2, 2);
void show(); y.show();
} ;
int shared::a;
I like C++ so much x.show();
return 0;
}
void shared::show()
{ I like Rupesh sir
cout << "This is static a: " << a;
cout << "\nThis is non-static b: " << b; cout << "\n";
}
 static
variable
variable
a redeclared
a declared
outside
inside
theclass
class
but, storage
using is not allocated
scope resolution operator.
 Storage for the variable will be allocated
Objects and Classes 75
class A
{
Program : Static data member
int x;
public:
A()
{
cout << "A's constructor called " << endl;
}
};

class B
{
static A a;
public:
B()
{
cout << "B's constructor called " << endl;
}
};

A B::a; // definition of a
Output:
int main() A's constructor called
{
B's constructor called
B b1, b2, b3;
return 0;
B's constructor called
} B's constructor called
Static Member Functions
Static Member Functions
 Static member functions can access only static members of the
class.
 Static member functions can be invoked using class name, not
object.
I like C++ so much
 There cannot be static and non-static version of the same
function.
I like Rupesh sir
 They cannot be virtual.
 They cannot be declared as constant or volatile.
 A static member function does not have this pointer.

Objects and Classes 78


Program: Static Member function
class item
{
int number;
static int count;// static variable declaration
public:
I like C++ so much
void getdata(int a){
number = a;

}
count++;
I like Rupesh sir
static void getcount(){
cout<<”value of count: “<<count;
}
};
int item :: count; // static variable definition

Objects and Classes 79


Program: Static Member function
int main()
{
item a,b,c;

a.getdata(100);
I like C++ so much
item::getcount();

I like Rupesh sir


b.getdata(200);
item::getcount();

c.getdata(300); Output:
item::getcount(); value of count: 1
return 0; value of count: 2
} value of count: 3

Objects and Classes 80


Friend Function
Friend Function
 In C++ a Friend Function that is a "friend" of a given class is
allowed access to private and protected data in that class.
 A friend function is a function which is declared using friend
keyword.
I like C++ so much
Class Class
class A I like Rupesh sir class B
{ {
private: private:
int numA; Friend Function int numB;
public: void add() public:
void setA(); { void setB();
friend void add(); Access friend void add();
}; numA, numB };
}
Objects and Classes 82
Friend Function
 Friend function can be declared either in public or private part of
the class.
 It is not a member of the class so it cannot be called using the
object.
I like C++ so much
 Usually, it has the objects as arguments.
Syntax:
class ABC I like Rupesh sir
{
public:
……………………………………………
friend void xyz(argument/s); //declaration
……………………………………………
};
Objects and Classes 83
Program: Friend Function
class numbers {
int num1, num2;
public:
void setdata(int a, int b);
friend int add(numbers N);
}; I like C++ so much
void numbers :: setdata(int a, int b){
num1=a;
num2=b;
I like Rupesh sir
int main()
{
}
numbers N1;
int add(numbers N){
N1.setdata(10,20);
return (N.num1+N.num2);
} cout<<”Sum = ”<<add(N1);
return 0;
}
Objects and Classes 84
class Box { Program: Friend
double width;
public: Function
friend void printWidth( Box );
void setWidth( double wid );
};
void Box::setWidth( double wid ) {
width = wid;
}
void printWidth(Box b) {
cout << "Width of box : " << b.width;
}
int main( ) {
Box box;
box.setWidth(10.0);
printWidth( box );
return 0;
}
class base
{ Program: Friend
int val1,val2;
public:
Function
void get(){
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob){
return float(ob.val1+ob.val2)/2;
}
int main(){
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
}
Member function, friend to another class
class X {  Member functions of one class can
……………………………………… be made friend function of another
int f(); class.
};
class Y{  The function f is a member of
……………………………………… I like C++ so much
class X and a friend of class Y.
friend int X :: f();
}; I like Rupesh sir

Objects and Classes 87


Friend function to another class
Class Class
class A class B
{ {
private: private:
Friend Function
int numA;
public:
I like void
C++add()so much int numB;
public:
void setA(); void setB();
I like Rupesh sir
friend void add();
{
Access
numA, numB
friend void add();
}; } };

Objects and Classes 88


Program: Friend function to another class
 Write a program to find out sum of two private data members
numA and numB of two classes ABC and XYZ using a common
friend function. Assume that the prototype for both the classes
will be int add(ABC, XYZ);

I like C++ so much


I like Rupesh sir

Objects and Classes 89


class XYZ; //forward declaration Program: Friend to another class
class ABC { class XYZ {
private: private:
int numA; int numB;
public: public:
void setdata(){ void setdata(){
numA=10; numB=25;
} }
friend int add(ABC, XYZ); friend int add(ABC , XYZ);
}; };

int add(ABC objA, XYZ objB){


return (objA.numA + objB.numB);
}
int main(){
ABC objA; XYZ objB;
objA.setdata(); objB.setdata();
cout<<"Sum: "<< add(objA, objB);
}
class Square; // forward declaration Program: Friend
class Rectangle to another class
{
int width=5, height=6;
public:
friend void display(Rectangle , Square );
};
class Square
{
int side=9;
public:
friend void display(Rectangle , Square );
};
void display(Rectangle r, Square s)
{
cout<<"Rectangle:"<< r.width * r.height;
cout<<"Square:"<< s.side * s.side;
}
Program: Friend
int main () { to another class
Rectangle rec;
Square sq;
display(rec,sq);
return 0;
}
Use of friend function
 It is possible to grant a nonmember function access to the private
members of a class by using a friend function.
 It can be used to overload binary operators.

I like C++ so much


I like Rupesh sir

Objects and Classes 93


Constructors
What is constructor ?
A constructor is a block of code which is,
similar to member function
has same name as class name
I like C++ so much
called automatically when object of class created
I like Rupesh sir
A constructor is used to initialize the objects of class as soon as the
object is created.

Objects and Classes 95


Constructor
class car class car
{ Same {
private: private:
name as
float mileage; float mileage;
public: class name public:
void setdata() car()
{
cin>>mileage;
I like C++ so
Similar
member
to much {
cin>>mileage;

};
}
I like Rupesh
function sir
};
}

int main() int main()


Called
{ {
automatically
car c1,c2;
c1; car c1,c2;
c1;
on creation
c1.setdata();
of object
c2.setdata();
} }
Objects and Classes 96
Properties of Constructor
 Constructor should be declared in public class car
{
section because private constructor cannot private:
be invoked outside the class so they are float mileage;
useless. public:
car()
I like C++ so much
 Constructors do not have return types and
they cannot return values, not even void.
{
cin>>mileage;

I like Rupesh sir };


}

 Constructors cannot be inherited, even though a derived class can


call the base class constructor.
 Constructors cannot be virtual.
 They make implicit calls to the operators new and delete when
memory allocation is required.
Objects and Classes 97
Constructor (Cont…)
class Rectangle
{
int width,height;
public:
Rectangle(){
width=5;
height=6;
I like C++ so much
}
I like Rupesh sir
cout<<”Constructor Called”;

};
int main()
{
Rectangle r1;
return 0;
}
Objects and Classes 98
Types of Constructors
Types of Constructors
1) Default constructor
2) Parameterized constructor
3) Copy constructor

I like C++ so much


I like Rupesh sir

Objects and Classes 100


1) Default Constructor
 Default constructor is the one which invokes by default when
object of the class is created.
 It is generally used to initialize the default value of the data
members.
I like C++ so much
 It is also called no argument constructor.

class demo{ I like int


Rupesh
main() sir
int m,n; { Object d1
public: demo d1;
demo() m n
}
{ 10 10
m=n=10;
}
};
Objects and Classes 101
Program Constructor
class Area int main(){
{ Area A1;
private: A1.Calculate();
int length, breadth; Area A2;
public: A2.Calculate();
Area(){
length=5;
I like C++ so much
}
return 0;

breadth=2;
}
I like Rupesh sir
void Calculate(){
cout<<"\narea="<<length * breadth;
} A1 A2
};
length breadth length breadth
5 2 5 2
Objects and Classes 102
2) Parameterized Constructor
 Constructors that can take arguments are called parameterized
constructors.
 Sometimes it is necessary to initialize the various data elements of
different objects with different values when they are created.
I like C++ so much
 We can achieve this objective by passing arguments to the
constructor function when the objects are created.
I like Rupesh sir

Objects and Classes 103


Parameterized Constructor
 Constructors that can take arguments are called parameterized
constructors.
class demo
{
int m,n;
public: I like C++ so much
demo(int x,int y){ //Parameterized Constructor
m=x;
n=y; I like Rupesh sir
cout<<“Constructor Called“;
}
};
int main() d1
{ m n
demo d1(5,6);
} 5 6

Objects and Classes 104


Program Parameterized Constructor
 Create a class Distance having data members feet and inch.
Create parameterized constructor to initialize members feet and
inch.

I like C++ so much


I like Rupesh sir

Objects and Classes 105


3) Copy Constructor
 A copy constructor is used to declare and initialize an object from
another object using an object as argument.
 For example:
demo(demo &d); //declaration
I like C++//copy
demo d2(d1); soobject
much
OR demo d2=d1; //copy object
I like Rupesh sir
 Constructor which accepts a reference to its own class as a
parameter is called copy constructor.

Objects and Classes 106


3) Copy Constructor
 A copy constructor is used to initialize an object
from another object
using an object as argument.

 A Parameterized constructor which accepts a reference to its own


I like C++ so much
class as a parameter is called copy constructor.
I like Rupesh sir

Objects and Classes 107


Copy Constructor
class demo int main()
{ {
int m, n; demo obj1(5,6);
public: demo obj2(obj1);
demo(int x,int y){ demo obj2 = obj1;
m=x; }
n=y; I like C++ so much obj1
obj1 or x
cout<<"Parameterized Constructor";
} I like Rupesh sir m n
demo(demo &x){
5 6
m = x.m;
n = x.n;
obj2
cout<<"Copy Constructor";
} m n
}; 5 6

Objects and Classes 108


Program: Types of Constructor
 Create a class Rectangle having data members length and
width. Demonstrate default, parameterized and copy
constructor to initialize members.

I like C++ so much


I like Rupesh sir

Objects and Classes 109


Program: Types of Constructor
class rectangle{
int length, width; This is constructor
public: overloading
rectangle(){ // Default constructor
length=0;
width=0;
}
rectangle(int x, int y){// Parameterized
constructor
length = x;
width = y;
}
rectangle(rectangle &_r){ // Copy constructor
length = _r.length;
width = _r.width;
}
};
Program: Types of Constructor (Cont…)

int main()
{
rectangle r1; // Invokes default constructor
rectangle r2(10,20); // Invokes parameterized
constructor
rectangle r3(r2); // Invokes copy constructor
}
Destructor
Destructor class car
{
• Destructor is used to destroy the objects float mileage;
public:
that have been created by a constructor. car(){
• The syntax for destructor is same as that cin>>mileage;
}
for the constructor,
– the class name is used for the name of ~car(){
cout<<" destructor";
destructor, }
– with a tilde (~) sign as prefix to it.
};

Destructor
 never takes any argument nor it returns any value nor it has return
type.
 is invoked automatically by the complier upon exit from the
program.
 should be declared in the public section.
Program: Destructor
class rectangle int main()
{ {
int length, width; rectangle x;
public: // default
rectangle(){ //Constructor constructor is
length=0;
width=0; I like C++ so much
called
}
cout<<”Constructor Called”;
} I like Rupesh sir
~rectangle() //Destructor
{
cout<<”Destructor Called”;
}
// other functions for reading, writing and
processing can be written here
};
Objects and Classes 114
Program: Destructor
class Marks{ int main( )
public: {
int maths; Marks m1;
int science; Marks m2;
//constructor return 0;
Marks() { I like C++ so much
cout << "Inside Constructor"<<endl;
}

}
I like Rupesh sir
cout << "C++ Object created"<<endl;

//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
Objects and Classes 115
Operator Overloading
Operator Overloading
int a=5, b=10,c; Operator + performs
c = a + b; addition of
integer operands a, b

I like C++ so much


time t1,t2,t3;
t3 = t1 + t2;
Operator + performs
addition of
I like Rupesh sirobjects of type time
string str1=“Hello” Operator + concatenates
string str2=“Good Day”; two strings str1,str2
string str3;
str3 = str1 + str2;
Objects and Classes 117
Operator overloading
 Function overloading allow you to use same function name for
different definition.
 Operator overloading extends the overloading concept to
operators, letting you assign multiple meanings to C++ operators
 Operator overloading giving the normal C++ operators such as +, *
I like C++ so much
and == additional meanings when they are applied with user
defined data types.
I like Rupesh sir
Operator Purpose

Some of C++ Operators * As pointer, As multiplication


are already overloaded As insertion, As bitwise shift left
<<
& As reference, As bitwise AND

Objects and Classes 118


Operator Overloading
int a=5, b=10,c;
c = a + b;
Operator + performs addition of integer
operands a, b
class time
{
int hour, minute;I like C++ so much
};
I like Rupesh sir
Operator + performs addition of objects of
type time t1,t2
time t1,t2,t3;
t3 = t1 + t2;
string str1=“Hello”,str2=“Good Day”;
str1 + str2; Operator + concatenates two strings
str1,str2
Objects and Classes 119
Operator Overloading
 Specifying more than one definition for an operator in the same
scope, is called operator overloading.
 You can overload operators by creating “operator functions”.
Syntax:
I like C++ so much
return-type operator op-symbol(argument-list)
{

}
// statements
I like Rupesh sir
Keyword substitute the operator

Example:
void operator + (arguments);
int operator - (arguments);
class-name operator / (arguments);
float operator * (arguments);
Objects and Classes 120
Overloading Binary operator + int main()
class complex{ {
int real,imag; complex c1(4,6),c2(7,9);
public: complex c3;
complex(){ c3 = c1 + c2;
real=0; imag=0; c1.disp();
} c2.disp();
complex(int x,int y){ c3.disp();
real=x; imag=y; return 0;
} }
void disp(){
cout<<"\nreal value="<<real<<endl;
cout<<"imag value="<<imag<<endl;
}
complex operator + (complex);
};
complex complex::operator + (complex c){
complex tmp;
tmp.real = real + c.real; Similar to function call
tmp.imag = imag + c.imag;
return tmp;
c3=c1.operator +(c2);
}
Binary Operator Arguments
result = obj1.operator symbol (obj2);//function notation
result = obj1 symbol obj2; //operator notation
complex operator + (complex x)
{
complex tmp;
tmp.real = real + x.real;
tmp.imag = imag + x.imag;
return tmp;
}

result = obj1.display();
void display()
{
cout<<"Real="<<real;
cout<<"Imaginary="<<imag;
}
Operator Overloading
 Operator overloading is compile time polymorphism.
 You can overload most of the built-in operators available in C++.
+ - * / % ^
& | ~ ! , =
< I like C++ so much
> <= >= ++ --
<< >> == != && ||
+= I like Rupesh sir
-= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []

Objects and Classes 123


Operator Overloading using
Friend Function
Invoke Friend Function in operator overloading
result = operator symbol (obj1,obj2);//function notation
result = obj1 symbol obj2; //operator notation

friend complex operator +(complex c1,complex c2)


{
complex tmp;
tmp.r=c1.r+c2.r;
tmp.i=c1.i+c2.i;
return tmp;
}
int main()
{
complex c1(4,7),c2(5,8);
complex c3;
c3 = c1 + c2;
c3 = operator +(c1,c2);
}
Overloading Binary operator ==
class complex{ int main()
int r,i; {
public: complex c1(5,3),c2(5,3);
complex(){ if(c1==c2)
r=i=0;} cout<<"objects are equal";
complex(int x,int y){ else
r=x; cout<<"objects are not equal";
i=y;} return 0;
void display(){ }
cout<<"\nreal="<<r<<endl;
cout<<"imag="<<i<<endl;}
int operator==(complex);
};
int complex::operator ==(complex c){
if(r==c.r && i==c.i)
return 1;
else
return 0;}
Overloading Unary Operator
Overloading Unary operator − int main()
class space { {
int x,y,z; space s1(5,4,3);
public: s1.display();
space(){ -s1;
x=y=z=0;} s1.display();
space(int a, int b,int c){ return 0;
x=a; y=b; z=c; } }
void display(){
cout<<"\nx="<<x<<",y="<<y<<",z="<<z;
}
void operator-();
};
void space::operator-() {
x=-x;
y=-y;
z=-z;
}
Overloading Unary operator −− int main()
class space { {
int x,y,z; space s1(5,4,3);
public: s1.display();
space(){ --s1;
x=y=z=0;} s1.display();
space(int a, int b,int c){ return 0;
x=a; y=b; z=c; } }
void display(){
cout<<"\nx="<<x<<",y="<<y<<",z="<<z;
}
void operator--();
};
void space::operator--() {
x--;
y--;
z--;
}
Overloading Prefix and Postfix operator
class demo
{ int main()
int m; {
public: demo d1(5);
demo(){ m = 0;} ++d1;
demo(int x) d1++;
{ }

}
m = x;
I like C++ so much
void operator ++()
{
++m;
I like Rupesh sir
cout<<"Pre Increment="<<m;
}
void operator ++(int)
{
m++;
cout<<"Post Increment="<<m;
}
};
Objects and Classes 130
Invoking Operator Function
 Binary operator
operand1 symbol operand2
 Unary operator
operand symbol
symbol operand
I like C++ so much
I like Rupesh
 Binary operator using friend function
operator symbol (operand1,operand2)
sir
 Unary operator using friend function
operator symbol (operand)

Objects and Classes 131


Rules for operator overloading
 Only existing operator can be overloaded.
 The overloaded operator must have at least one operand that is
user defined type.
 We cannot change the basic meaning and syntax of an operator.
I like C++ so much
I like Rupesh sir

Objects and Classes 132


Rules for operator overloading (Cont…)
 When using binary operators overloaded through a member
function, the left hand operand must be an object of the relevant
class.
 We cannot overload following operators.
I like C++ soName
Operator
much
I like
. and Rupesh
.* Class siroperator
member access

:: Scope Resolution Operator

sizeof() Size Operator

?: Conditional Operator

Objects and Classes 133


Type Conversion
Type Conversion
F = C * 9/5 + 32 If different data types are mixed in expression, C++
applies automatic type conversion as per certain
rules.
float int

int a;
I like C++
float b = 10.54; so much
a = 10;
 float is converted to integer automatically
a = b; by complier.

integer float
I like Rupesh sir
 basic to basic type conversion.

(Basic) (Basic)

 An assignment operator causes automatic type conversion.


 The data type to the right side of assignment operator is automatically
converted data type of the variable on the left.

Objects and Classes 135


Type Conversion
Time t1;
int m;
m = t1;

integer Time  class type will not be converted to


(Basic) I like C++ so much
(Class) basic type OR basic type will not
be converted class type
t1 = m;
I like Rupesh sir
automatically.

Time integer
(Class) (Basic)

Objects and Classes 136


Type Conversion
 C++ provides mechanism to perform automatic type conversion if
all variable are of basic type.
 For user defined data type programmers have to convert it by
using constructor or by using casting operator.
I like C++ so much
 Three type of situation arise in user defined data type conversion.
1. I tolike
Basic type Rupesh
Class type sir
(Using Constructors)
2. Class type to Basic type (Using Casting Operator Function)
3. Class type to Class type (Using Constructors & Casting
Operator Functions)

Objects and Classes 137


(1) Basic to class type conversion
 Basic to class type can be achieved using constructor.
class sample
{ int main()
int a; {
public: int m=10;
sample(){} I like C++ so much sample s;
s = m;
sample(int x){
a=x; I like Rupesh sir s.disp();
return 0;
}
void disp(){ }
cout<<"The value of a="<<a;
}
};

Objects and Classes 138


(2) Class to basic type conversion
 The Class type to Basic type conversion is done using casting operator
function.
 The casting operator function should satisfy the following conditions.
1. It must be a class member.

I like C++ so much


2. It must not mention a return type.
3. It must not have any arguments.

Syntax:
I like Rupesh sir
operator destinationtype()
{
....
return
}

Objects and Classes 139


Program: Class to basic type conversion
class sample int main()
{ {
float a; sample S;
public: int y= S;//Class to Basic
sample() conversion
{ cout<<"The value of y="<<y;

}
a=10.23;
I like C++ so much
}
return 0;

operator int() //Casting operator

{
I like Rupesh sir
function
Explicit type conversion
int x; y = int (S);
x=a;
return x;
Automatic type conversion
} y = S;
};

Objects and Classes 140


Program: Class to basic type conversion
class vector{ int main()
int a[5]; {
public: vector v;
vector(){ int len;
for(int i=0;i<5;i++) len = v;
}
I like C++ socout<<“Length
a[i] = i*2; much of V="<<len;
return 0;
};
operator int(); I like Rupesh} sir
vector:: operator int() {
int sum=0;
for(int i=0;i<5;i++)
sum = sum + a[i];
return sum;}

Objects and Classes 141


(3) Class type to Class type
 It can be achieved by two ways
1. Using constructor
2. Using casting operator function

I like C++ so much


I like Rupesh sir

Objects and Classes 142


class alpha
{
Program: Class type to Class type
int commona;
public: class beta
alpha(){} {
alpha(int x) int commonb;
{ public:
commona = x; beta(){}
} beta(int x)
int getvalue() {
{ commonb = x;
return commona; }
} beta(alpha temp) //Constructor
}; {
commonb = temp.getvalue();
int main() }
{ operator alpha() //operator function
alpha obja(10); {
beta objb(obja); return alpha(commonb);
beta objb(20); }
obja = objb; };
}
class stock2 ;
class stock1{ Program: Type Conversion
int code , item ;
float price ;
public :
stock1 ( int a , int b , int c ) {
code = a ; item = b ; price = c ;
}
void disp () {
cout << " code " << code << " \n " ;
cout << " items " << item << " \n " ;
cout << " price per item Rs. " << price << " \n " ;
}
int getcode (){ return code; }
int getitem (){ return item ; }
int getprice (){ return price ; }
operator float () {
return ( item*price ) ;
}
};
class stock2{
int code ;
Program: Type Conversion
float val ;
public :
stock2 () {
code = 0; val = 0 ;
}
stock2( int x , float y ){
code = x ; val = y ;
}
void disp () {
cout << " code " << code << " \n " ;
cout << " total value Rs. " << val << " \n " ;
}
stock2( stock1 p ) {
code = p.getcode() ;
val = p.getitem() * p.getprice() ;
}
};
int main() Program: Type Conversion
{
stock1 i1 ( 101 , 10 ,125.0 ) ;
stock2 i2 ;
float tot_val = i1;
i2 = i1 ;
cout << " Stock Details : Stock 1 type " << " \n " ;
i1.disp ();
cout << " Stock Value " << " - " ;
cout << tot_val << " \n " ;
cout << " Stock Details : Stock 2 type " << " \n " ;
i2.disp () ;
return 0 ;
}
Thank You

You might also like