2. Prerequisite
C fundamentals
Virtual compiler
for c&c++
https://www.onlinegdb.com/online_c+
+_compiler
https://www.programiz.com/cpp-
programming/online-compiler/
https://www.tutorialspoint.com/compile_cpp_o
nline.php
https://ide.codingblocks.com/
Before starting c++ revise following
c programs
C Program to Swap Two Numbers
C "Hello, World!" Program
Program to Check Even or Odd
Factors of a Positive Integer
C Program to Calculate the Power of a Number
2
3. Unit 1: Introduction to Object Oriented Programming
Introduction,
Need of OOP
Characteristic of OOP,
Basic Concepts of OOP, Benefits of OOP,
Object Oriented Languages
Applications of OOP
Installation and Compilation of C++
Simple C++ program
Structure of C++ Program
Keywords, Identifiers, and constants
Basic Data types, User defined data types, Derived data types, Symbolic Constants.
3
4. Need of OOP
Introduction:
Programmers write instructions in various programming languages to perform their
computation tasks such as:
(i) Machine level Language
(ii) Assembly level Language
(iii) High level Language
4
5. High level language
hhe programming logic rather than
the underlying hardware
components such as memory
addressing.igher level of
abstraction from the computer, and
focuses more on t
High level
The first high-level programming languages were
designed in the 1950s. Now there are dozens of
different languages, including Ada , Algol, BASIC,
COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal,
and Prolog. Such languages are considered high-
level because they are closer to human
languages and farther from machine languages.
In contrast, assembly languages are considered
low-level because they are very close to machine
languages.
In the procedure oriented
approach, the problem is
viewed as sequence of
things to be done such as
reading , calculation and
printing.
Procedure oriented
programming basically
consist of writing a list of
instruction or actions for the
computer to follow and
organizing these instruction
into groups known as
functions
Procedure oriented
● Emphasis is on doing
things(algorithm)
● 2. Large programs are divided into
smaller programs known as functions.
● 3. Most of the functions share global
data
● 4. Data move openly around the
system from function to function
● 5. Function transforms data from one
form to another.
“Object oriented
programming as an
approach that provides a
way of modularizing
programs by creating
partitioned memory area for
both data and functions that
can be used as templates for
creating copies of such
modules on demand”.
Object oriented
Emphasis is on doing rather than procedure.
2. programs are divided into what are known as objects.
3. Data structures are designed such that they
characterize the objects.
4. Functions that operate on the data of an object are
tied together in the data structure.
5. Data is hidden and can’t be accessed by external
functions.
6. Objects may communicate with each other through
functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design
5
6. Procedure oriented
The disadvantage of the procedure
oriented programming languages is:
1. Global data access
2. It does not model real word problem
very well
3. No data hiding
6
8. oops
1. Emphasis is on doing rather than procedure.
2. programs are divided into what are known
as objects.
3. Data structures are designed such that they
characterize the objects.
4. Functions that operate on the data of an
object are tied together in the data structure.
5. Data is hidden and can’t be accessed by
external functions.
6. Objects may communicate with each other
through functions.
7. New data and functions can be easily added.
8
9. Basics of C++
/ Online C++ compiler
to run C++ program
online
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
float average;
cout<< "Enter
number1:";
cin >> a;
cout<< "Enter number2:";
cin>> b;
c=a+b;
cout<<"Addition= "<<c<<endl;
average=c/2;
cout<<"Average = "<<average<<endl;
return(0);
} 9
10. Resolution Operator example in C++.
#include <iostream>
using namespace std;
int a = 20;
int main()
{
int a = 10;
cout << "Value of local a: " << a << endl;
//use of SRO (::) to access global variable.
cout << "Value of global a: " << ::a << endl;
return 0;
}
Output
Value of local a: 10
Value of global a: 20
10
11. Reference variable example in C++
#include <iostream>
using namespace std;
int main()
{
int a=10;
/*reference variable is alias of other variable,
It does not take space in memory*/
int &b = a;
cout << endl << "Value of a: " << a;
cout << endl << "Value of b: " << b << endl;
return 0;
}
Output
Value of a: 10
Value of b: 10
11
12. function as a LVALUE using reference variable example in C++
#include <iostream>
using namespace std;
int var ;
int& fun()
{
return var;
}
int main()
{
//Function used as LVALUE
fun() = 10;
cout << "Value of var : " << var << endl;
return 0;
Value of var : 10
12
13. Default Argument example in C++.
#include <iostream>
using namespace std;
//Default argument must be trailer.
int sum(int x, int y=10, int z=20)
{
return (x+y+z);
}
int main()
{
cout << "Sum is : " << sum(5)
<< endl;
cout << "Sum is : " << sum(5,15)
<< endl;
cout << "Sum is : " << sum(5,15,25)
<< endl;
return 0;
}
Sum is : 35
Sum is : 40
Sum is : 45
13
14. #include <iostream>
using namespace std;
void swapByValue( int a , int b );
void swapByRef ( int &a, int &b );
void swapByAdr ( int *a, int *b );
int main()
{
int x = 10;
int y = 20;
cout << endl;
cout << "Value before Swapping x:" << x << " y:"
<< y << endl;
swapByValue( x , y ); /*In call by value swapping
does not reflect in calling function*/
cout << "Value After Swapping x:" << x << " y:"
<< y << endl << endl;
cout << "Value before Swapping x:" << x << " y:"
<< y << endl;
swapByRef( x , y ); /*Swapping reflect but
reference does not take space in memory*/
cout << "Value After Swapping x:" << x << " y:"
<< y << endl << endl;
x = 50;
y = 100;
cout << "Value before Swapping x:" << x << " y:"
<< y << endl;
swapByAdr( &x , &y ); /*Swapping reflect but
pointer takes space in memory*/
cout << "Value After Swapping x:" << x << " y:"
<< y << endl << endl;
return 0;
}
14
15. void swapByValue( int a , int b )
{ int c;
c = a;
a = b;
b = c;
}
void swapByRef( int &a , int &b )
{
int c;
c = a;
a = b;
b = c;
}
void swapByAdr( int *a , int *b )
{
int c;
c = *a;
*a = *b;
*b = c;
}
Out put
Value before Swapping x:10 y:20
Value After Swapping x:10 y:20
Value before Swapping x:10 y:20
Value After Swapping x:20 y:10
Value before Swapping x:50 y:100
Value After Swapping x:100 y:50
15
16. Function overloading example in C++.
#include <iostream>
using namespace std;
void printChar();
void printChar( char c );
void printChar( char c, int num );
void printChar(int num, char c);
int main()
{
printChar();
printChar('#');
printChar(10,'$');
printChar('@',10);
cout<< endl;
return 0;
}
void printChar()
{
cout<< endl<<"%";
}
void printChar( char c )
{
cout<< endl<< c;
}
void printChar( char c, int num )
{
int i=0;
cout<< endl;
for(i=0; i< num; i++)
cout<< c;
}
16
17. void printChar(int num, char c)
{
int i=0;
cout<< endl;
for(i=0; i< num; i++)
cout<< c;
}
Output
17
18. C++ program to read string using cin.getline()
Since cin does not read complete string using spaces, stings terminates as you input space. While
cin.getline() – is used to read unformatted string (set of characters) from the standard input device
(keyboard). This function reads complete string until a give delimiter or null match.
In this program will read details name, address, about of a person and print in different lines, name
will contain spaces and dot, address will contain space, commas, and other special characters,
same about will also contains mixed characters. We will read all details using cin.getline()
function and print using cout.
cin.getline() example in C++.
18
19. C++ program to read string using cin.getline
*
#include <iostream>
using namespace std;
//macro definitions for maximum length
of variables
#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100
#define MAX_ABOUT_LENGTH 200
using namespace std;
int main()
{
char
name[MAX_NAME_LENGTH],address[MAX_ADDRE
SS_LENGTH],about[MAX_ABOUT_LENGTH];
cout << "Enter name: ";
cin.getline(name,MAX_NAME_LENGTH);
cout << "Enter address: ";
cin.getline(address,MAX_ADDRESS_LENGTH)
;
cout << "Enter about yourself
(press # to complete): ";
cin.getline(about,MAX_ABOUT_LENGTH,'#')
; //# is a delimiter
cout << "nEntered details are:";
cout << "Name: " << name << endl;
cout << "Address: " << address <<
endl;
cout << "About: " << about << endl;
return 0;
}
19
20. Output
Enter name: Mr. Mike Thomas
Enter address: 101, Phill Tower, N.S., USA
Enter about yourself (press # to complete): Hello there!
I am Mike, a website designer.
My hobbies are creating web applications.#
Entered details are:Name: Mr. Mike Thomas
Address: 101, Phill Tower, N.S., USA
About: Hello there!
I am Mike, a website designer.
My hobbies are creating web applications.
20
21. #include <iostream>
using namespace std;
enum shape
{circle,
rectangle,triangle
};
int main() {
// Write C++ code here
cout << "Enter shape of code";
int code;
while(code>=circle && code <=
triangle)
{
swich (code)
{
case circle:
cout << "shape of code is circle";
break;
case rectangle:
cout << "shape of code is
rectangle;
break;
case triangle:
cout << "shape of code is triangle;
break;
}
cout << "bye";
return 0;
}
}
21
22. Enumerated data type
-This is user-defined type which provides a way for attaching names to numbers
there by increasing understanding of the code
- This facility provides an alternative means for creating symbolic constants
-Syntax
enum shape{circle,triangle,rectangle};
enum colour {red,blue,green,yellow};
enum position {off,on};
22
23. Example enumerated data type
#include <iostream>
using namespace std;
enum week { Monday, Tuesday,
Wednesday, Thursday, Friday,
Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
}
Output
Day: 5
23
25. Structure data type
Structure is a collection of variables of different data types under a single name.
The members of structure variable is accessed using a dot (.) operator.
Syntax
Struct Person
{
char name[50];
int age;
float salary;
};
25
26. Structure
When a structure is created, no memory is allocated.
Once you declare a structure person as above. You can define a structure variable as: P1
When structure variable is defined, only then the required memory is allocated by the compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of int is 4
bytes and memory of char is 1 byte.
Hence, 58 bytes of memory is allocated for structure variable P1.
26
28. Out put
Enter Full name: sdfg hjk
Enter age: 23
Enter salary: 1024
Displaying Information.
Name: sdfg hjk
Age: 23
Salary: 1024
28
29. Union C++ data type
A union is a user-defined type similar to structs except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only hold
one member value at a time.
The size of a union variable will always be the size of its largest element.
29
30. UNION(c) Example
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes",
sizeof(uJob));
printf("nsize of structure = %d bytes",
sizeof(sJob));
return 0;
}
Out put
size of union = 32 bytes
size of structure = 40 bytes
30
31. Class c++ data type
A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for
an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.
● A Class is a user defined data-type which has data members and member functions.
● Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behavior of
the objects in a Class.
● In the above example of class Car, the data member will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc.
31
32. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the
curly brackets and terminated by a semicolon at the end.
32
33. Declaring Objects:
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to
create objects
33
34. Class -user defined data types
Class: A class in C++ is the building block, that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data members
and member functions, which can be accessed and used by creating an instance of
that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class
and wheels, speed limits, mileage are their properties.
34
35. ● A Class is a user defined data-type which has data members and member functions.
● Data members are the data variables and member functions are the functions used to manipulate
these variables and together these data members and member functions defines the properties and
behavior of the objects in a Class.
● In the above example of class Car, the data member will be speed limit, mileage etc and member
functions can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
35
36. Class
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside
the curly brackets and terminated by a semicolon at the end.
36
37. Declaring Objects:
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
37
38. Class example
#include <iostream>
# include <string>
using namespace std;
class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string
variable)
void printname()
{
cout << "function string name is: " <<
myString<<"n";
}
};
int main()
{
MyClass myObj; // Create an object of
MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
myObj.printname();
// Print values
cout << "Variable is: "<< myObj.myNum
<< "n";
cout << "vaiable string name is
:"<<myObj.myString;
return 0; 38
39. Out put
function string name is: Some text
Variable is: 15
vaiable string name is :Some text
39
40. Multiple object
#include <iostream>
# include <string>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
// Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
// Print attribute values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year <<
"n";
cout << carObj2.brand << " " <<
carObj2.model << " " << carObj2.year <<
"n";
return 0;
}
40
42. Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
● Inside class definition
● Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using the dot
syntax (.):
42
43. Inside (function inside class)
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
void myMethod( ) { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;}
}
43
44. Function outside class
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function
declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
} 44
45. Array
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
int myNum[3] = {10, 20, 30};
Loop through an array
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "n";
45
46. C++ references
A reference variable is a "reference" to an existing variable, and it is created with the &
operator:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
string food = "Pizza";
string &meal = food;
cout << food << "n"; // Outputs Pizza
cout << meal << "n"; // Outputs Pizza
46
47. Pointers
Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as
well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:
How to use a pointer?
● Define a pointer variable
● Assigning the address of a variable to a pointer using unary operator (&) which returns the address of
that variable.
● Accessing the value stored in the address using unary operator (*) which returns the value of the
variable located at the address specified by its operand.
The reason we associate data type to a pointer is that it knows how many bytes the data is stored in. When
we increment a pointer, we increase the pointer by the size of data type to which it points.
47
49. Unit 2
Introduction,
Operators in C++
`Expression and their types.
The Main Function, Function Prototyping, Call by reference, Return by Reference, Inline Function
Operator Overloading
Classes, Objects and memory, Structures and classes, Specifying a class
A C++ program with Class, Nesting of member function, Arrays of Objects, Objects as Function
arguments
49
50. Operators in c++
Operation Arithmatic
+ ,Addition
- ,Subtraction
● ,Multiplication
/ ,Division
% ,Modulo Operation (Remainder after division)
Ope
rato
r
Example Equivalent
to
= a = b; a = b;
+= a += b; a = a +
b;
-= a -= b; a = a -
b;
*= a *= b; a = a *
b;
/= a /= b; a = a /
b;
%= a %= b; a = a %
b;
50
51. Rational operator
Operator Meaning Example
== Is Equal To 3 == 5 gives us false
!= Not Equal To 3 != 5 gives us true
> Greater Than 3 > 5 gives us false
< Less Than 3 < 5 gives us true
>= Greater Than or Equal
To
3 >= 5 give us false
<= Less Than or Equal To 3 <= 5 gives us true
51
52. Logical operator
&& expression1 && expression2 Logical AND.
True only if all the operands
are true.
|| expression1 || expression2 Logical OR.
True if at least one of the
operands is true.
! !expression Logical NOT.
True only if the operand is
false.
52
53. Operator Description
& Binary AND
| Binary OR
^ Binary XOR
~ Binary One's Complement
<< Binary Shift Left
>> Binary Shift Right
53
54. Other operators
Operator Description Example
sizeof returns the size of data
type
sizeof(int); // 4
?: returns value based on
the condition
string result = (5 >
0) ? "even" : "odd";
// "even"
& represents memory
address of the operand
# // address of
num
. accesses members of
struct variables or class
objects
s1.marks = 92;
-> used with pointers to
access the class or
ptr->marks = 92;
54
55. Function in c++
A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs,
we can call the function.
The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ]) { co
55
56. Function Declaration
A function declaration tells the compiler about the number of parameters function takes, data-types of parameters
and return type of function. Putting parameter names in function declaration is optional in the function declaration,
but it is necessary to put them in the definition. Below are an example of function declarations. (parameter names are
not there in below declarations)
56
57. Parameter Passing to functions
The parameters passed to function are called actual parameters. For example, in the above program
10 and 20 are actual parameters.
The parameters received by function are called formal parameters. For example, in the above
program x and y are formal parameters.
There are two most popular ways to pass parameters.
Pass by Value: In this parameter passing method, values of actual parameters are copied to function’s
formal parameters and the two types of parameters are stored in different memory locations. So any
changes made inside functions are not reflected in actual parameters of caller.
57
58. Pass by Reference
Pass by Reference Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in
actual parameters of caller.
Parameters are always passed by value in C. For example. in the below code, value of x is not modified using the function fun()
#include <iostream>
using namespace std;
void fun(int x) {
x = 30;
}
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
. 58
60. Function
Main Function:
The main function is a special function. Every C++ program must contain a function named main. It serves as the
entry point for the program. The computer will start running the code from the beginning of the main function.
Types of main Function
unction:
1) The first type is – main function without parameters :
2) Second type is main function with parameters :
// With Parameters
int main(int argc, char * const argv[])
{
...
return 0;
} 60
61. The reason for having the parameter option for the main function is to allow input
from the command line.
When you use the main function with parameters, it saves every group of characters
(separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a
return statement in the code. The number that is returned is used to inform the calling
program what the result of the program’s execution was. Returning 0 signals that
there were no problems.
61
62. #include <iostream>
using namespace std;
void fun(int *ptr)
{
*ptr = 30;
}
int main()
{
// Write C++ code here
int x = 20;
cout << "x = " << x;
fun(&x);
cout << "x = " << x;
return 0;
}
x = 20x = 30
62
63. In line function
In C++, we can declare a function as inline. This copies the function to the location of the function call in
compile-time and may make the program execution faster.
C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is
expanded in line when it is called. When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler
at compile time. Inline function may increase efficiency if it is small.
The syntax for defining the function inline is:
inline returnType functionName(parameters) {
// code
}
63
64. In line function
#include <iostream>
using namespace std;
inline void displayNum(int num) {
cout << num << endl;
}
int main() {
// first function call
displayNum(5);
// second function call
displayNum(8);
// third function call
displayNum(666);
return 0;
}
Output:
5
8
666
64
65. Default Arguments in function
Float amount (float principal,int period,float rate=0.15)
value= amount (5000,7)
Float amount (float principal,int period=7,float rate)
This is illegal
65
66. Classes and objects
Suppose, we need to store the length, breadth, and height of a rectangular room and calculate its
area and volume.
To handle this task, we can create three variables, say, length, breadth, and height along with the
functions calculateArea() and calculateVolume().
However, in C++, rather than creating separate variables and functions, we can also wrap these
related data and functions in a single place (by creating objects). This programming paradigm is
known as object-oriented programming.
66
67. We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
A class is a logical method of grouping data and functions in the same construct.
An object is a data structure that encapsulates data and functions in a single construct.
class className{
permission_label_1
member1;
permission_label_2
member2;
}object_name;
67
68. Example of Class and object
#include <iostream>
using namespace std;
class person
{
int age;
char name[30];
public:
void get_details(void)
{
cout<< "Enter your Name:"<<endl;
cin>>name;
cout<< "Enter your Age:"<<endl;
cin>>age;
}
void display_details(void);
};
void person::display_details(void)
{
cout<< "NAME:"<<name<<endl;
cout<< "AGE:"<<age<<endl;
}
int main()
{
person p;
p.get_details();
p.display_details();
return 0; 68
70. Write a C++ Program to display Names, Roll No., and grades of 3 students who have
appeared in the examination. Declare the class of name, Roll No. and grade. Create an
array of class objects. Read and display the contents of the array.
70
71. #include <iostream>
using namespace std;
#define MAX 10
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
void getDetails(void); //member function to get
student's details
void putDetails(void); //member function to
print student's details
};
void student:: getDetails(void) //member
function definition, outside of the class
{
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc=(float)total/500*100;
}
void student:: putDetails(void) //member
function definition, outside of the class
{
cout << "Student details:n";
cout << "Name:"<< name << ",Roll
Number:" << rollNo << ",Total:" << total <<
",Percentage:" <<
71
72. int main()
{
student std[MAX]; //array of objects
creation
int n,loop;
cout << "Enter total number of students: ";
cin >> n;
for (loop=0;loop< n; loop++)
{
cout << "Enter details of student " <<
loop+1 << ":n";
std[loop].getDetails();
}
cout << endl;
for(loop=0;loop< n; loop++)
{
cout << "Details of student " << (loop+1) <<
std[loop].putDetails();
}
return 0;
}
72
73. Arrays of Objects
Array can be a group of any data type including struct,similarly we can have arrays
of variables that are of the types class. Such variables are called arrays of objects
Class employee
{char name [30];
Float age;
Public :
Void getdata(void);
Void putdata(void);
}
Example
employee manager[4];
employee foreman[10];
employee worker [6];
It contains objects
manager,foreman,worker
How to accesses?
73
74. #include <iostream>
using namespace std;
class employee
{
private:
char name[30];
float age;
public:
void getDetails(void); //member function to
get student's details
void putDetails(void); //member function to
print student's details
};
void employee ::getDetails(void)
{
cout << "Enter name: " ;
cin >> name;
cout << "Enter age:";
cin>> age;
}
void employee ::putDetails(void)
{
cout << name << "n";
cout << age << "n";
}
74
75. const int size =3;
int main() {
int i;
employee manager [size];
for(i=0;i<size+1;i++)
{cout << "n Details of manager"<<i+1<< "n";
manager[i].getDetails();
}
// Write C code here
for (i=0;i<size+1;i++)
{cout << "n Details of manager"<<i+1<< "n";
manager[i].putDetails();
}
return 0;
}
output
Details of manager1
Enter name: a
Enter age:23
Details of manager2
Enter name: s
Enter age:34
Details of manager1
a
23
Details of manager2
S
34
75
76. Practice example
Write A C++ Program To Find Electricity Bill Of A Person.
unit tarrif
>100 RS.1.20 per unit
>200 RS.2 per unit
>300 RS.3 per unit
#include<iostream.h>
#include<conio.h>
class ebill
{
private:
int cno;
char cname[20];
int units;
double bill;
public:
void get()
{
cout<<"Enter Customer No,Name and No. of
Units" <<endl;
cout<<"Enter Customer No : ";
cin>>cno;
cout<<"nEnter Customer Name : ";
cin>>cname;
cout<<"nEnter No. of Units used : ";
cin>>units;
}
void put()
{
cout<<"nCustomer No is : "<<cno;
cout<<"nCustomer Name is :
"<<cname;
cout<<"nNumber of Units
Consumed : "<<units; 76
78. program to find average marks of N student each having M subjects in a
class.
#include <iostream>
using namespace std;
int main ( )
{
struct student
{
int rn ;
int sub[10] ;
};
struct student st[50] ;
int i, j,n,m,total;
float av;
cout<<"n Enter the Number of
Students in the Class : ";
cin>> n ;
cout<<"nEnter the Number of Subjects
Each Student has Taken : " ;
cin>> m ;
for (i=0;i<n;i++)
{
total = 0 ;
cout<<"nEnter the Rollno
of "<<i+1<<" Student : ";
cin>> st[i].rn;
cout<<"nEnter the Marks :
";
for (j=0;j<m;j++)
{
cout<<"nEnter the
Marks of "<<j+1 <<" Subject : ";
cin>> st[i ].sub[j ];
total = total + st[i 78
79. ].sub[j ];
}
av = (float) total / m
;
cout<<"AVERAGE
Marks of "<<i+1<<" Student = "<< av;
}
return(0);
}
79
80. Unit 03
Constructor and Destructor:
Operators in C++, `Expression and their types. Control structure, Parameterized
Constructor, Multiple Constructors in a class, Constructor with Default arguments,
Copy constructor, Dynamic Constructor, Constant, Object Destructors.
80
81. Operators in c++
operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from
the first
A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-
numerator
B / A will give 2
% Modulus Operator and remainder
of after an integer division
B % A will give 0
++ Increment operator, increases
integer value by one
A++ will give 11
81
82. Operator Description Example
== Checks if the values of two
operands are equal or not, if yes
then condition becomes true.
(A == B) is not true.
!= Checks if the values of two
operands are equal or not, if
values are not equal then
condition becomes true.
(A != B) is true.
> Checks if the value of left
operand is greater than the value
of right operand, if yes then
condition becomes true.
(A > B) is not true.
82
83. < Checks if the value of left
operand is less than the value of
right operand, if yes then
condition becomes true.
(A < B) is true.
>= Checks if the value of left
operand is greater than or equal
to the value of right operand, if
yes then condition becomes true.
(A >= B) is not true.
<= Checks if the value of left
operand is less than or equal to
the value of right operand, if yes
then condition becomes true.
(A <= B) is true.
83
84. Logical operator
Operator Description Example
&& Called Logical AND operator. If
both the operands are non-zero,
then condition becomes true.
(A && B) is false.
|| Called Logical OR Operator. If
any of the two operands is non-
zero, then condition becomes
true.
(A || B) is true.
! Called Logical NOT Operator.
Use to reverses the logical state
of its operand. If a condition is
true, then Logical NOT operator
will make false.
!(A && B) is true.
84
85. Bitwise operator
Operator Description Example
& Binary AND Operator copies a bit
to the result if it exists in both
operands.
(A & B) will give 12 which is 0000
1100
| Binary OR Operator copies a bit
if it exists in either operand.
(A | B) will give 61 which is 0011
1101
^ Binary XOR Operator copies the
bit if it is set in one operand but
not both.
(A ^ B) will give 49 which is 0011
0001
~ Binary Ones Complement
Operator is unary and has the
effect of 'flipping' bits.
(~A ) will give -61 which is 1100
0011 in 2's complement form due
to a signed binary number. 85
86. << Binary Left Shift Operator. The
left operands value is moved left
by the number of bits specified
by the right operand.
A << 2 will give 240 which is
1111 0000
>> Binary Right Shift Operator. The
left operands value is moved
right by the number of bits
specified by the right operand.
86
87. Assignment operator
Operator Description Example
= Simple assignment operator,
Assigns values from right side
operands to left side operand.
C = A + B will assign value of A +
B into C
+= Add AND assignment operator, It
adds right operand to the left
operand and assign the result to
left operand.
C += A is equivalent to C = C + A
-= Subtract AND assignment
operator, It subtracts right
operand from the left operand
and assign the result to left
operand.
C -= A is equivalent to C = C - A
87
88. *= Multiply AND assignment
operator, It multiplies right
operand with the left operand
and assign the result to left
operand.
C *= A is equivalent to C = C * A
/= Divide AND assignment operator,
It divides left operand with the
right operand and assign the
result to left operand.
C /= A is equivalent to C = C / A
%= Modulus AND assignment
operator, It takes modulus using
two operands and assign the
result to left operand.
C %= A is equivalent to C = C %
A
88
89. <<= Left shift AND assignment
operator.
C <<= 2 is same as C = C << 2
>>= Right shift AND assignment
operator.
C >>= 2 is same as C = C >> 2
89
90. MISC operators
r.NoOperator & Description1
sizeof
sizeof operator returns the size of a variable. For
example, sizeof(a), where ‘a’ is integer, and will
return 4.
2
Condition ? X : Y
Conditional operator (?). If Condition is true then it
returns value of X otherwise returns value of Y.
3
,
Comma operator causes a sequence of operations
to be performed. The value of the entire comma
expression is the value of the last expression of the
comma-separated list.
4
. (dot) and -> (arrow)
Member operators are used to reference individual
members of classes, structures, and unions.
5
Cast
Casting operators convert one data type to
another. For example, int(2.2000) would return 2.
6
&
Pointer operator & returns the address of a
variable. For example &a; will give actual address
of the variable.
7
*
Pointer operator * is pointer to a variable. For
90
91. Constructor
A constructor is a special function called the constructor which enables an objects of
its class.
The constructor is invoked whenever an object of its associated class is created.It is
called constructor because it constructs the values of data members of the class.
91
92. Default constructor
A constructor without any arguments or with default value for every argument, is said to be default constructor
. #include <iostream>
using namespace std;
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
/tmp/sPPQk1dafF.o
a: 10
b: 20
92
93. Parameterized Constructors
#include <iostream>
using namespace std;
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor
declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the
constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year <<
"n";
cout << carObj2.brand << " " <<
carObj2.model << " " << carObj2.year <<
"n";
return 0;
} 93
95. Expressions in c++
An expression can consist of one or more operands, zero or more operators to compute a value. Every expression produces some value which is
assigned to the variable with the help of an assignment operator.
An expression can be of following types:
● Constant expressions
● Integral expressions
● Float expressions
● Pointer expressions
● Relational expressions
● Logical expressions
● Bitwise expressions
● Special assignment expressions
95
96. Expression containing constant Constant value
x = (2/3) * 4 (2/3) * 4
extern int y = 67 67
int z = 43 43
static int a = 56 56
96
97. Integral Expressions
An integer expression is an expression that produces the integer value as output after performing all the explicit and implicit
conversions.
Float Expressions
A float expression is an expression that produces floating-point value as output after performing all the explicit and implicit
conversions.
The following are the examples of float expressions:
1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.
97
98. 1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)
Pointer Expressions
A pointer expression is an expression that produces address value as an output.
The following are the examples of pointer expression:
1. &x
2. ptr
3. ptr++
4. ptr-
98
99. Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either true or false. It is also
known as a boolean expression. When arithmetic expressions are used on both sides of the relational operator, arithmetic
expressions are evaluated first, and then their results are compared.
The following are the examples of the relational expression:
1. a>b
2. a-b >= x-y
3. a+b>80
99
100. Logical Expressions
A logical expression is an expression that combines two or more relational expressions and produces a bool type value. The logical
operators are '&&' and '||' that combines two or more relational expressions.
The following are some examples of logical expressions:
1. a>b && x>y
2. a>10 || b==5
Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are basically used to shift the bits.
For example:
x=3
x>>3 // This statement means that we are shifting the three-bit position to the right.
In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x' by three-bit position to the right. Let's understand through the
diagrammatic representation.
100
101. Copy constructor
Constructor overloading:
A class with two or more construct functions with the same name but with different parameters or arguments
and other data types is called Constructor overloading.
Copy Constructors:
Definition of copy constructor is given as “A copy constructor is a method or member function which
initialize an object using another object within the same class”.
A copy constructor is of two types:
1. Default Copy Constructor.
2. User-Defined Copy Constructor.
Default Constructor:
101
102. Copy constructor
C++ compiler will create a default constructor which copies all the member variables as it is when the copy constructor is not
defined.
User-Defined Constructor:
The user defines the user-defined constructor.
Syntax for user defined constructor:
Class_Name (Class_Name &obj) {
// body of constructor
}
Here obj is the reference that is being initialised to another object.
102
103. Uses of Copy Constructor
1. When we initialize an object by another object of the same class.
2. When we return an object as a function value.
3. When the object is passed to a function as a non-reference parameter.
103
104. Problem
#include <iostream>
using namespace std;
class ABC
{
public: int x;
ABC (int a){ // this is
parameterized constructor
x=a;
}
ABC (ABC &i){ // this is copy
constructor
x = i.x;
}
};
int main ()
{
ABC a1(40); // Calling the
parameterized constructor.
ABC a2(a1); // Calling the copy
constructor.
cout<<a2.x;
return 0;
}
Output
40
104
105. Copy Constructor Types
There are two ways in which copy constructor copies, and they are:
1. Shallow copy.
2. Deep copy.
Let’s go through these topics one by one.
Shallow Copy
● It is the process of creating a copy of an object by copying data of all the member
variables as it is.
● Only a default Constructor produces a shallow copy.
● A Default Constructor is a constructor which has no arguments.
105
107. Example Shallow Copy
#include <iostream>
using namespace std;
class Opp {
int a;
int b;
int *z;
public: Opp() {
z=new int;
}
void input(int x, int y, int l) {
a=x;
b=y;
*z=l;
}
void display() {
cout<<"value of a:" <<a<<endl;
cout<<"value of b:" <<b<<endl;
cout<<"value of z:" <<*z<<endl;
}
};
int main() {
Opp obj1;
obj1.input(4,8,12);
Opp obj2 = obj1;
obj2.display();
return 0;
}
107
108. output
value of a:4
value of b:8
value of z:12
● In the above figure, both ‘obj1’ and ‘obj2’ will be having the same input and both the
object variables will be pointing to the same memory locations.
● The changes made to one object will affect another one.
● This particular problem is solved by using the user-defined constructor, which uses
deep copy.
108
109. Deep Copy
● It dynamically allocates memory for the copy first and then copies the actual value.
● In a deep copy, both objects which have to copy and another which has to be copied will be
having different memory locations.
● So, the changes made to one will not affect another.
● This is used by a user-defined copy constructor.
109
110. Example of Deep Copy
#include<iostream>
using namespace std;
class Number {
private: int a;
public: Number(){} //default
constructor Number (int n) {
Number(int n){
a=n;
}
Number(Number &x) {
a=x.a;
cout<<"copy constructor is
invoked";
}
void display() {
cout<<"value of a:"<<a<<endl;
}
};
int main() {
Number N1(100); // create an object
and assign value to member variable
Number N2(N1); // invoke user
defined copy constructor
N1.display ();
N2.display ();
return 0;
}
110
111. Output
copy constructor is invokedvalue of a:100
value of a:100
In the above example, N1 and N2 are the two objects. ‘N2’ is the object which stores the value
of objec’N1’. ‘N1’ takes 100 as input and will initialise to ‘N2’. ➢ Both N1 and N2 will have
different locations.
Changes made to one will not affect the other.
111
112. Difference between Copy Constructor and Assignment Operator
Copy Constructor Assignment Operator
It is an overloaded constructor. It is an operator.
The new object is initialized with an object
already existing.
Value of one object is assigned to another object
both of which exists already.
Here, both the objects use different or separate
memory locations.
Here, different variables points to the same
location but only one memory location is used.
The compiler provides a copy constructor if
there is no copy constructor defined in the class.
Bitwise copy will be made if the assignment
operator is not overloaded.
Copy Constructor is used when a new object is
being created with the help of the already
existing element.
Assignment operator is used when we need to
assign an existing object to a new object
112
113. The differences between assignment and initialisation.
Consider the following code segment:
MYClass a;
MYClass b=a;
➢ Here, the variable b is initialized to a because it is created as a copy of another variable. When b is
created, it will go from containing garbage data directly to holding a copy of the value of a with no
intermediate step.
113
114. However, if we rewrite the code as
MYClass a, b;
b=a;
➢ Then two is assigned the value of one. Note that before we reach the line b=a, B already contains a value.
This is the difference between assignment and initialisation. When a variable is created is set to hold a new
value, it is being assigned.
114
115. We can make the copy constructor private, but when we make the constructor private,
that class’s objects cannot be copied. This is useful when our class has pointer
variables or dynamically allocated resources. In such a situation, we can either write
our copy constructor or make a private copy constructor so that the user gets compiler
errors rather than something at runtime.
115
116. Problem statement
Define a class to represent a bank account. Include the following members
1. Name of depositor
2. Account number
3. Type of account
4. Balance amount in the account
Member functions
1.To assign initial values 2. To deposit an amount 3. To withdraw an amount
after checking the balance 4. To Display name and balance
116
117. Dynamic constructor
Constructor can allocate dynamically created memory to the object and thus
object is going to use memory region which is dynamically created by the
constructor.,whenever allocation of memory is done dynamically using new
inside a constructor, it is called dynamic constructor. By using dynamic
constructor in C++, you can dynamically initialize the objects.
1.The dynamic constructor does not create the memory of the object
but it creates the memory block that is accessed by the object.
2. You can also gives arguments in the dynamic constructor you want
to declared as
117
118. #include <iostream>
using namespace std;
class Mania
{
const char* ptr;
public:
// default constructor
Mania()
{
// allocating memory at run time
ptr = new char[15];
ptr = "Learning Mania";
}
void display()
{
cout << ptr;
}
};
int main()
{
Mania obj1;
obj1.display();
}
118
119. #include <iostream>
using namespace std;
class Mania
{
int num1;
int num2;
int *ptr;
public:
// default constructor (here, it is dynamic
constructor also)
Mania()
{
num1 = 0;
num2 = 0;
ptr = new int;
//dynamic constructor with parameters
Mania(int x, int y, int z)
{
num1 = x;
num2 = y;
ptr = new int;
*ptr = z;
}
void display()
{
cout << num1 << " " << num2 << " " <<
*ptr;
}
};
119
121. Destructors
The destructors in C++ can be defined as a member function which
destructs or deletes an object. The destructor names are the same as the
class name but they are preceded by a tilde (~). And it also a good
practice to declare the destructor after the end of using constructor. A
destructor function is called automatically when the object goes out of
scope i.e.
121
122. Example of destructor
#include <iostream>
using namespace std;
class ABC
{
public:
ABC () //constructor defined
{
cout << "Hey look I am in constructor"
<< endl;
}
~ABC() //destructor defined
{
cout << "Hey look I am in
destructor" << endl;
}
};
int main()
{
ABC cc1; //constructor is called
cout << "function main is terminating...."
<< endl;
/*....object cc1 goes out of scope ,now
destructor is being called...*/
return 0;
} //end of program
122
123. cont…..
Hey look I am in constructor
function main is terminating....
Hey look I am in destructor
123
124. Unit 3
Unit 4:Inheritance:
Class fundamentals, declaring objects, assigning object
references variables,
introducing methods, constructors, overloading method,
using objects as
parameters,
argument passing, returning objects, recursion, use of
static and final key word, 124
125. Question bank I
1.Write a C++ program to find the sum of individual digits of a positive
integer.
2. Write a C++ Program to generate first n terms of Fibonacci sequence.
3.Write a C++ program to generate all the prime numbers between 1 and n,
where n is a value supplied by the user
4.Write a C++ Program to find both the largest and smallest number in a list
of integers.
5.Write a program Illustrating Class Declarations, Definition, and Accessing
Class Members.
125
126. 6.Write a C++ Program to illustrate default constructor,parameterized
constructorand copy constructors.
7.Write a Program to Implement a Class STUDENT having following members:
Data members Member Description
sname - Name of the student , Marks array - Marks of the student
total- Total marks obtained ,Tmax -Total maximum marks
Member functions Member Description assign()- Assign Initial Values ,compute() to
Compute Total, Average display() to Display the Data
126
127. 8. Write a c++ program to declare a “book ” having data membebers book_name,
Author,price,and function members to accept data and display book of maximum
price
9. Write a c++ program to declare a class “staff ” having data members name,
basic salary, HRA ,DA , and calculate gross salary accept and display data of one
staff
Where DA 74.5 % basic,HRA 30% basic , Gross salary basic+HRA+DA
127
128. Write a difference between copy constructor and assignment
operator
What is deep and shallow copy constructor
With example write relational ,and integral expressions i c++
What is pass by value and pass by functions in c++
Explain the difference between structure and union
128