Notes Unit 1
Notes Unit 1
Faculty:Dr.Shubha Rao V
Object Oriented Programming using C++
Procedural languages
A procedural language is a type of computer programming language that specifies a series of
well-structured steps and procedures within its programming context to compose a program. It
contains a systematic order of statements, functions and commands to complete a
computational task or program.
Procedural language is also known as imperative language.
A procedural language, as the name implies, relies on predefined and well-organized
procedures, functions or sub-routines in a program’s architecture by specifying all the steps
that the computer must take to reach a desired state or output.
The procedural language segregates a program within variables, functions, statements and
conditional operators.
Procedures or functions are implemented on the data and variables to perform a task.
These procedures can be called/invoked anywhere between the program hierarchy and by other
procedures as well.
Procedural language is one of the most common types of programming languages in use, with
notable languages such as C/C++, Java, ColdFusion and PASCAL.
An object is a representation of a real-time entity and consists of data and methods or functions
that operate on data.
This way, data, and functions are closely bound and data security is ensured.
In OOP, everything is represented as an object and when programs are executed, the objects
interact with each other by passing messages.
An object need not know the implementation details of another object for communicating.
Apart from objects, OOP supports various features which are listed below:
Classes
Faculty:Dr.Shubha Rao V
Encapsulation
Abstraction
Inheritance
Polymorphism
Using OOP, we write programs using classes and objects by utilizing the above features.
On the other hand, programming languages like C++ and Java are said to be partial object-
oriented programming languages.
C++ language was designed with the main intention of using object-oriented features to C language.
Although C++ language supports the features of OOP like Classes, objects, inheritance, encapsulation,
abstraction, and polymorphism, there are few reasons because of which C++ is classified as a partial
object-oriented programming language.
This is the first violation of Pure OOP language where everything is represented as an object.
C++ supports all the OOP features, it also provides features that can act as a workaround for these
features, so that we can do without them. This makes C++ a partial Object-oriented programming
language.
Faculty:Dr.Shubha Rao V
OOP FEATURES
CLASSES & OBJECTS
An object is a basic unit in object-oriented programing.
An object contains data and methods or functions that operate on that data.
Objects take up space in memory.
A class, on the other hand, is a blueprint of the object.
An object can be defined as an instance of a class.
A class contains a template of the object and does not take any space in the memory.
Thus instead of defining these similar data and functions in these different objects, we define a
blueprint of these objects which is a class called Car. Each of the objects above will be instances
of this class car.
ABSTRACTION
Abstraction is the process of hiding irrelevant information from the user.
For Example, when we are driving the car, first we start the engine by inserting a key. We are not
bothered of the process that goes on in the background for starting the engine.
Using abstraction in programming, we can hide unnecessary details from the user. By using abstraction
in our application, the end user is not affected even if we change the internal implementation.
ENCAPSULATION
Encapsulation is the process using which data and the methods or functions operating on them are
bundled together.
In OOP we achieve encapsulation by wrapping data variables and member functions together as one
bundle.
Data Hiding: This is achieved by making some members private and having public functions to access
these data members.
INHERITANCE
Using inheritance object of one class can inherit or acquire the properties of the object of another class.
Inheritance provides reusability of code.
Faculty:Dr.Shubha Rao V
We can design a new class by acquiring the properties and functionality of another class and in this
process,.We can add new functionality to the new class.
POLYMORPHISM
Polymorphism means many forms.
DYNAMIC BINDING
OOP supports dynamic binding in which function call is resolved at runtime. This means that the code
to be executed as a result of a function call is decided at runtime. Virtual functions are an example of
dynamic binding.
MESSAGE PASSING
In OOP, objects communicate with each other using messages. When objects communicate, information
is passed back and forth between the objects. A message generally consists of the object name, method
name and actual data that is to be sent to another object.
ADVANTAGES OF OOP
#1) Reusability
OOP allows the existing code to be reused through inheritance.
#2) Modularity
As we modularize the program in OOP, it’s easy to modify or troubleshoot the program if a problem
occurs or new feature or enhancement is to be added. Modularization also helps in code clarity and
makes it more readable.
#3) Flexibility
OOP helps us with flexible programming using the polymorphism feature.
As polymorphism takes many forms, we can have operators or functions that will work with many
objects and thus save us from writing different functions for each object.
#4) Maintainability
Maintaining code is easier as it is easy to add new classes, objects, etc without much restructuring or
changes.
Faculty:Dr.Shubha Rao V
A C++ program is structured in a specific and particular manner. In C++, a program is divided into the
following three sections:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
#include is a specific preprocessor command that effectively copies and pastes the entire text
of the file, specified between the angle brackets, into the source code.
The file <iostream>, which is a standard file that should come with the C++ compiler, is short
for input-output streams. This command contains code for displaying and getting an input
from the user.
namespace is a prefix that is applied to all the names in a certain set. iostream file defines
two names used in this program - cout and endl.
The starting point of all C++ programs is the main function.
This function is called by the operating system when your program is executed by the computer.
{ signifies the start of a block of code, and } signifies the end.
The name cout is short for character output and displays whatever is between the << brackets.
Symbols such as << can also behave like functions and are used with the keyword cout.
The return keyword tells the program to return a value to the function int main
After the return statement, execution control returns to the operating system component that
launched this program.
Execution of the code terminates here.
Open a terminal
$ gedit file.cpp
Faculty:Dr.Shubha Rao V
Type the program code in the editor
$ g++ file.cpp --- to compile the code here executable is stored in default file a.out
$ ./a.out --- to execute the code
OR
$ g++ file.cpp –o file --- to compile the code here executable is user defined name
$ ./file --- to execute the code
The most important function of C/C++ is main() function. It is mostly defined with a return type of
int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are given after
the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first argument is
the number of command line arguments and second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line arguments passed by the
user including the name of the program. So if we pass a value to a program, value of argc would
be 2 (one for argument and one for program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers
to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.
Example:
#include <iostream>
Faculty:Dr.Shubha Rao V
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;}
Reference Variables:
For example, if your name is Mohan Das but at home, your family members call you Mohan . The
same person is having two names
The declaration and use of this type of variable are different from the usual variables we use but very
much similar to the pointer variables.
Syntax
int x=6;
int &y=x;
Example
Faculty:Dr.Shubha Rao V
Output:
when we declare int x=6 , a memory is allocated whose name is x and value is 6.
Assume its address is 1000
int &y=x;
A new name is given for the same location.
Example: In the program given below address of x and y are printed. The output illustrates the
location is same and address is same. The location has two different names.
Faculty:Dr.Shubha Rao V
Functions:
1. Call by value
2. Call by Address
3. Call be reference
Actual Parameters are the parameters that appear in the function call statement.
Formal Parameters are the parameters that appear in the declaration of the
function which has been called.
Call By Value:
Example:
#include <iostream>
using namespace std;
void add(int a, int b){
cout<<"address of a inside the function is"<<&a<<endl;
cout<<"address of b inside the function is is"<<&b<<endl;
Faculty:Dr.Shubha Rao V
a = a + 10;
b = b + 10;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
int main()
{
int x = 10;
int y = 20;
cout<<"address of x in main function is"<<&x<<endl;
cout<<"address of y in main function is"<<&y<<endl;
add(x,y);
cout<<"Value of x = "<<x<<endl;
cout<<"Value of y = "<<y<<endl;
return 0;
}
Output:
The above program two locations x and y are created in the main function. Let us assume each one has
address 1000 and 1010. When the function is called, the values are passed to the function. The call by
value method is used over here.
In the function definition we have two parameters a and b. These are two new memory locations with
address 2000 and 2010. The values from x and y are copied to a and b. Thus any changes we make to
a and y are not reflected in x and y of main function. The lines highlighted in grey changes values in
the location a and b not in x and y.
Faculty:Dr.Shubha Rao V
Call by Refernce
In the call by reference, both formal and actual parameters share the same value.
Both the actual and formal parameter points to the same address in the memory.
Faculty:Dr.Shubha Rao V
That means any change on one type of parameter will also be reflected by other.
Calls by reference are preferred in cases where we do not want to make copies of objects or
variables, but rather we want all operations to be performed on the same copy.
Example
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << "Value in Function main before function call: "<< x <<endl;
increment(x);
cout << "Value in Function main: "<< x <<endl;
return 0;
}
Output:
Faculty:Dr.Shubha Rao V
Call by address
In the call by address method, both actual and formal parameters indirectly
share the same variable.
In this type of call mechanism, pointer variables are used as formal parameters.
The formal pointer variable holds the address of the actual parameter; hence, the
changes done by the formal parameter is also reflected in the actual parameter.
Faculty:Dr.Shubha Rao V
Example
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout<<"address of x in main function "<<&x<<endl;
increment(&x); //Passing address of x
cout << "Value in Function main: "<< x <<endl;
return 0;
}
Faculty:Dr.Shubha Rao V
Output:
Note:
In Function declarations and function definitions first line we can identify the method used for
function calls
Structure in c++
Difference between structure and class :
In C++, a structure works the same way as a class, except for just two small differences. The most
important of them is hiding implementation details. A structure will by default not hide its
implementation details from whoever uses it in code, while a class by default hides all its
implementation details and will therefore by default prevent the programmer from accessing them.
The following table summarizes all of the fundamental differences.
Class Structure
Members of a class are private by default. Members of a structure are public by default.
Faculty:Dr.Shubha Rao V
Class Structure
It is declared using the class keyword. It is declared using the struct keyword.
// Program 1 // Program 2
// C++ Program to demonstrate that // C++ Program to demonstrate that
// Members of a class are private // members of a structure are public
// by default // by default.
using namespace std; #include <iostream>
A class is declared using the class keyword, and a structure is declared using the struct keyword.
Inheritance is possible with classes, and with structures.
Faculty:Dr.Shubha Rao V
Class Structure
Both structures and classes can have methods inside the definition.
Class:
A class is a blueprint for the object. 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.
CREATE A CLASS
A class is defined in C++ using keyword class followed by the name of the class.
The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.
class className {
// some data
// some functions
};
For example:
class Room {
public:
double length;
double breadth;
double height;
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}
};
Faculty:Dr.Shubha Rao V
The variables length, breadth, and height declared inside the class are known as data members. And,
the functions calculateArea() and calculateVolume() are known as member functions of a class.
C++ 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, we need to create objects.
We can create objects of Room class (defined in the above example) as follows:
// sample function
void sampleFunction() {
// create objects
Room room1, room2;
}
int main(){
// create objects
Room room3, room4;
}
Here, two objects room1 and room2 of the Room class are created in sampleFunction(). Similarly, the
objects room3 and room4 are created in main().
we can create objects of a class in any function of the program. We can also create objects of a class
within the class itself, or in other classes.
Also, we can create as many objects as we want from a single class.
C++ Access Data Members and Member Functions
We can access the data members and member functions of a class by using a . (dot) operator. For
example,
room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2.
room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.
#include <iostream>
using namespace std;
Faculty:Dr.Shubha Rao V
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
In this program, we have used the Room class and its object room1 to calculate the area and volume of
a room.
In main(), we assigned the values of length, breadth, and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
We then called the functions calculateArea() and calculateVolume() to perform the necessary
calculations.
Faculty:Dr.Shubha Rao V
Note the use of the keyword public in the program. This means the members are public and can be
accessed anywhere from the program.
As per our needs, we can also create private members using the private keyword. The private members
of a class can only be accessed from within the class.
For example,
class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}
Here, a and function1() are private. Thus they cannot be accessed from outside the class.
On the other hand, b and function2() are accessible from everywhere in the program.
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
Faculty:Dr.Shubha Rao V
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
The above example is nearly identical to the first example, except that the class variables are now
private.
Since the variables are now private, we cannot access them directly from main(). Hence, using the
following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function initData() to initialize the private variables via the function
parameters double len, double brth, and double hgt.
Note : If we don’t give any access specifier inside class, access specifier of member variables and
methods are private.
Faculty:Dr.Shubha Rao V
#include<iostream>
using namespace std;
class demo
{
private:
int x,y;
void input()
{
Faculty:Dr.Shubha Rao V
cout<<”this function is a private function”;
}
public:
int z;// this a public variable
void read()
{
Input(); // private method can be called in public section with object and dot operator
cout<<”enter two numbers”<<endl;
cin>>x>>y;
// variables can be accessed directly need not give object name and dot operaotor
}
void display()
{
read() // public members can also be called in any member function irrespective of public
or private
Cout<<”Numbers are x and y=”<<x<<”\t”<<y;
}
};
int main()
{
demo d1; // object is created. It is also called instance of a class or a variable of the class.
d1.read();
// valid as read is a public function.
// Observe read function should be invoked using object and dot operator.
d1.display(); //valid
demo d2; // another object is created.
d2.read();
d1.display();
x=10;
y=20;
input();
// these the statements are invalid as its member variables we cannot access directly out side
// the class
d1.x=100;
d1.y=200;
d1.input();
// these three statements are invalid as they are private member variables. You can not access
them outside the class.
read();
display();
z=100;
// These statements are invalid as they are members of the class even though public we cannot
access them directly out side the class.
Faculty:Dr.Shubha Rao V
d1.read();
d1.display();
z=100;
// These statements are valid as memebrs are public and they invoked with object and dot
operator
}
In the above program a class demo is defined with member variables x and y . Read() and display()
are called member methods. Wrapping data variables and methods/functions together we are achieving
encapsulation.
The class definition has two parts i) private section ii) public section. We can include both member
variables and member methods in side private section and also in public section.
The members(variables & methods) can be accessed directly inside the class. The members declared in
private section can be accessed only inside the class. The members inside private section can be
accessed both inside & outside the class. While accessing inside the class they can be used directly.
When accessing outside the class it should be preceded with object name and dot operator.
Before using a member of a class, it is necessary to allocate the required memory space to
that member.
The way the memory space for data members and member functions is allocated is different regardless
of the fact that both data members and member functions belong to the same class.
The memory space is allocated to the data members of a class only when an object of the class is
declared, and not when the data members are declared inside the class. Since a single data member can
have different values for different objects at the same time, every object declared for the class has an
individual copy of all the data members.
On the other hand, the memory space for the member functions is allocated only once when the class
is defined. In other words, there is only a single copy of each member function, which is shared among
all the objects. For instance, the three objects, namely, book1, book2 and book3 of the class book have
individual copies of the data members title and price. However, there is only one copy of the member
functions getdata () and putdata () that is shared by all the three objects.
Faculty:Dr.Shubha Rao V
Member functions can be defined outside the class by using scope resolution operator. Class definition
should have declaration or prototype of the function.
Example
Class demo
{
int x; // if we don’t specify the access specifier then its is by default private
public:
void read(); // function prototype
void display();
int add(int);
};
void demo::read()
{
cin>>x>>y;
}
void demo :: display()
{
Cout<<”x=”<<x<<”y=”<<y;
}
int demo::add(int a)
{
return(x+a);
}
Faculty:Dr.Shubha Rao V
int main()
{
Int j=100;
demo d1;
d1.read();
d1.display();
int res=d1.add(j);
}
Add function in the above code is having return type and one parameter being passed.
Faculty:Dr.Shubha Rao V
cout<<"\n\nTotal marks "<<total;
}
int main() {
student stu;
stu.getdata() ;
stu.tot_marks() ;
return 0;
}
Array of 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.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of objects.
Example#1:
Storing more than one Employee data. Let’s assume there is an array of objects for
storing employee data emp[50].
class Employee
{
Faculty:Dr.Shubha Rao V
int id;
char name[30];
public:
// Declaration of function
void getdata();
// Declaration of function
void putdata();
};
// Driver code
int main()
{
// This is an array of objects having maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].getdata();
Note: Member functions can be defined either inside the class or outside the class.
Faculty:Dr.Shubha Rao V
Non member fuctions are not part of class. They are regular functions.
Example:
#include<iostream.h>
Using namespace std;
Int add(int a,int b)
{
Return(a+b);
}
Int main()
{
Int x,y;
x=100;
y=200;
z=add(x,y); non member function or regular function
cout<<z;
}
1.Given that an EMPLOYEE class contains following members: Employee Number, Employee
Name, Basic, DA, IT, Net Salary. Member functions: to read the data, to calculate Net Salary and to
print data members. Write a C++ program to read the data of N employees and compute Net Salary
of each employee. (Dearness Allowance (DA) = 52% of Basic and Income Tax (IT) = 30% of the
gross salary. Net Salary = Basic + DA - IT).
#include <iostream>
using namespace std;
class employee{
int emp_num;
string emp_name;
float basic, da,it,gross_salary,net_salary;
public:
void read();
void display();
float find_net_salary();
};
void employee:: read()
{
Faculty:Dr.Shubha Rao V
void employee::display()
{
cout<<"\nEmployee number: ";
cout<<emp_num<<endl;
cout<<"Employee Name: ";
cout<<emp_name<<endl;
cout<<"Employee Basic Salary: ";
cout<<basic<<endl;
cout<<"Employee dear allowance: ";
cout<<da<<endl;
cout<<"Income tax: ";
cout<<it<<endl;
cout<<"Employee Net salary: ";
cout<<net_salary<<endl;
}
float employee::find_net_salary(){
da = basic * 0.52;
gross_salary = basic + da;
it = gross_salary * 0.30;
net_salary = (basic + da) - it;
return net_salary;
}
int main()
{
employee emp[100];
int number_of_emp, count;
cout<<"\nEnter the number of Employees : ";
cin>>number_of_emp;
for(count=0; count< number_of_emp; count++){
emp[count].read();
emp[count].find_net_salary();
}
cout<<"\nEMPLOYEE INFORMATION"<<endl;
for(count=0; count < number_of_emp; count++){
emp[count].display();
}
return 0;
}
2. Write a C++ program to Create array of objects of class student with data members for storing his
USN marks of six subjects for three tests and member functions to input display and calculate the avg
marks for each subject taking best two of three marks. Write a tester program to test these classes.
#include <iostream>
#include<algorithm>
Faculty:Dr.Shubha Rao V
using namespace std;
class Students {
string usn, name;
int marks[6][3];
float average[6];
public:
void input();
void display();
};
void Students::input() {
cout << "USN:";
cin >> usn;
cout << "Name:";
cin >> name;
for(int i=0; i<6; i++) {
cout << "Enter marks obtained in 3 tests in Subject " << i+1 << ":"<<endl; cin >>
marks[i][0] >> marks[i][1] >> marks[i][2];
int min_marks = min(marks[i][0], marks[i][1], marks[i][2]);
average[i] = float (marks[i][0] + marks[i][1] + marks[i][2] - min_marks)/2; }
void Students::display() {
cout << usn << "\t" << name << "\t";
for(float i : average) {
cout << i << " ";
Faculty:Dr.Shubha Rao V
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of Students:" << endl;
cin >> n;
Students std[n];
for (int i = 0; i < n; i++) {
cout << "\nEnter the details of Student-" << i+1 << endl;
std[i].input();
}
cout << "\nDetails of Students:" << endl << "USN\tName\tAverage Marks in 6 Subjects" <<
endl;
for (int i = 0; i < n; i++) {
std[i].display();
}
}
#include<iostream>
#include<string.h>
using namespace std;
Faculty:Dr.Shubha Rao V
class bank
{
int acno;
char nm[100], acctype[100];
float bal;
public:
read(int acc_no, char *name, char *acc_type, float balance)
{
acno=acc_no;
strcpy(nm, name);
strcpy(acctype, acc_type);
bal=balance;
}
void deposit();
void withdraw();
void display();
};
Faculty:Dr.Shubha Rao V
float balance;
cout<<"\n Enter Details: \n";
cout<<"-----------------------";
cout<<"\n Accout No. ";
cin>>acc_no;
cout<<"\n Name : ";
cin>>name;
cout<<"\n Account Type : ";
cin>>acc_type;
cout<<"\n Balance : ";
cin>>balance;
bank b1;
b1.read(acc_no, name, acc_type, balance);
b1.deposit(); //
b1.withdraw(); // calling member functions
b1.display(); //
while(1)
{
cout<<"\n1. Your Information\n2. Deposit\n3. Withdraw\nEnter your choice\n";
cin>>i;
if(i==1)
{
b1.display();
}
else if(i==2)
{
b1.deposit();
}
else if(i==3)
{
b1.withdraw();
}
else
return 0;
}
}