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

Notes Unit 1

Uploaded by

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

Notes Unit 1

Uploaded by

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

BMS COLLEGE OF ENGINEERING,BANGALORE

DEPT. OF INFORMATION SCIENCE & ENGINEERING


Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

A program written in procedural language contains one or more procedures.

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.

Object-Oriented Programming In C++


Object-oriented programming revolves around data.

The main programming unit of OOP is the object.

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

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism

Using OOP, we write programs using classes and objects by utilizing the above features.

A programming language is said to be a true object-oriented programming language if


everything it represents is using an object. Smalltalk is one language which is a pure object-
oriented programming language.
Ruby is also pure object oriented programming language.

On the other hand, programming languages like C++ and Java are said to be partial object-
oriented programming languages.

WHY C++ IS PARTIAL OOP?

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.

#1) Creation of class/objects is Optional


In C++, the main function is mandatory and is always outside the class. Hence, we can have only one
main function in the program and can do without classes and objects.

This is the first violation of Pure OOP language where everything is represented as an object.

#2) Use of Global Variables


C++ has a concept of global variables that are declared outside the program and can be accessed by any
other entity of the program. This violates encapsulation. Though C++ supports encapsulation with
respect to classes and objects, it doesn’t take care of it in case of global variables.

#3) Presence of a Friend Function


C++ supports a friend class or function that can be used to access private and protected members of
other classes by making them a friend. This is yet another feature of C++ that violates OOP paradigm.

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

Let us take an Example of a car object.


A car object named “Maruti” can have data such as color; make, model, speed limit, etc. and
functions like accelerate.
We define another object “ford”. This can have similar data and functions like that of the
previous object plus some more additions.
Similarly, we can have numerous objects of different names having similar data and functions
and some minor variations.

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.

By doing this, data is not easily accessible to the outside world.

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

Polymorphism is an important feature of OOP and is usually implemented as operator overloading or


function overloading. Operator overloading is a process in which an operator behaves differently in
different situations. Similarly, in function overloading, the same function behaves differently in
different situations.

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.

#5) Data and Information Hiding


OOP aids us in data hiding thereby keeping information safe from leaking. Only the data that is required
for the smooth functioning of the program are known to the user by hiding intrinsic details.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

Structure of a C++ Program:

A C++ program is structured in a specific and particular manner. In C++, a program is divided into the
following three sections:

1. Standard Libraries Section


2. Main Function Section
3. Function Body Section

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.

To practice the programs use Ubuntu or virtual machine

Open a terminal

$ gedit file.cpp

To open the terminal

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V
Type the program code in the editor

Save it with extension .cpp

We need to come back to the terminal

$ 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

Command Line arguments

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>

using namespace std;

int main(int argc, char** argv)


{

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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;}

Command Line Arguments

Reference Variables:

C++ gives us a new type of variable i.e a reference variable.

A reference variable as a nickname for our original variable.

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

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V
Output:

[user@localhost ~]$ g++ ref.cpp


[user@localhost ~]$ ./a.out
x=6 y=6
x=16 y=16
x=26 y=26

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

The highlighted text shows its same location.


Thus, reference variables are aliases to a variable

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:

Call by Value is a popularly used method.


Usually we will be using the call by value approach, as we do not want our original values of the
variables to be changed. In this method of call a function, only the values of the variables are passed.
This is achieved by creating dummy variables in memory.

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;

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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;

//Value of x is shared with a


void increment(int &a){
a++;
cout << "Value in Function increment: "<< a <<endl;
}

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:

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

As demonstrated in the diagram, both parameters point to different locations in


memory, but since the formal parameter stores the address of the actual parameter,
they share the same value.

Example

#include <iostream>
using namespace std;

//a stores the address of x


void increment(int *a){
cout<<"address of a is"<<&a<<endl;
cout<<"content of a in function "<<a<<endl;
(*a)++;
cout << "Value in Function increment: "<< *a <<endl;
}

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;
}

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

Output:

Observe the output we find address of x and content of a is same.


Address of a is different. It is a different memory location which holds address.

Note:
 In Function declarations and function definitions first line we can identify the method used for
function calls

Void function1(int ,int) -------- call be value

Void function2(int *,int *) --------call be address

Void function3(int &,int &) --------call be reference

Void function4(int,int*,int &) --------call by value, call by address, call by reference.

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

Class Structure

Member classes/structures of a class are private Member classes/structures of a structure are


by default. public by default.

It is declared using the class keyword. It is declared using the struct keyword.

It is normally used for data abstraction and


further inheritance. It is normally used for the grouping of data

// 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>

class Test { struct Test {


// x is private // x is public
int x; int x;
}; };

int main() int main()


{ {
Test t; Test t;
t.x = 20; // compiler error because x t.x = 20;
// is private
// works fine because x is public
return t.x; std::cout << t.x;
} }
Output: Output
prog.cpp: In function ‘int main()’: 20
prog.cpp:8:9: error: ‘int Test::x’ is private
int x;
^
prog.cpp:13:7: error: within this context
t.x = 20;
^

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

Class Structure

Both structures and classes can have methods inside the definition.

Class And Objects:

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;
}

};

Here, we defined a class named Room.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

Syntax to Define Object in C++


className objectVariableName;

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.

Similarly, the data members can be accessed as:

room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.

Example 1: Object and Class in C++ Programming


// Program to illustrate the working of // objects and class in C++ Programming

#include <iostream>
using namespace std;

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

Example 2: Using public and private in C++ Class


// Program to illustrate the working of
// public and private in C++ Class

#include <iostream>
using namespace std;

class Room {

private:
double length;
double breadth;
double height;

public:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

#include<iostream>
using namespace std;

class demo
{
private:
int x,y;
void input()
{

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

Member functions outside the class:

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);
}

The syntax for defining outside the class is :


Return-type class name :: functionname( parameters)

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V

int main()
{
Int j=100;
demo d1;
d1.read();
d1.display();
int res=d1.add(j);
}

A member function can have return value.


A member function can have parameters passed .

Add function in the above code is having return type and one parameter being passed.

ARRAYS AS CLASS MEMBERS IN C++


Arrays can be declared as the members of a class. The arrays can be declared as private, public or
members of the class.
To understand the concept of arrays as members of a class, consider this example.
Example: A program to demonstrate the concept of arrays as class members
The output of the program is
#include<iostream>
using namespace std;
class student {
int roll_no;
int marks[5];
public:
void getdata ();
void tot_marks ();
};
void student :: getdata () {
cout<<"\nEnter roll no: ";
cin>>roll_no;
for(int i=0; i<size; i++) {
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks {
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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].

// C++ program to implement array of objects


#include<iostream>
using namespace std;

class Employee
{

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

Faculty:Dr.Shubha Rao V
int id;
char name[30];
public:

// Declaration of function
void getdata();

// Declaration of function
void putdata();
};

// Defining the function outside


// the class
void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}

// Defining the function outside


// the class
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}

// 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();

cout << "Employee Data - " << endl;


// Accessing the function
for(i = 0; i < n; i++)
emp[i].putdata();
}

Note: Member functions can be defined either inside the class or outside the class.

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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()
{

cout<<"The employee number: ";


cin>>emp_num;
cout<<"Enter employee name: ";
cin>>emp_name;
cout<<"enter employee basic salary: ";
cin>>basic;
}

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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>

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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();
};

int min(int x, int y, int z)


{
if((x<y) && (x<y))
{
return x;
}
else if((y<x) && (y<z))
{
return y;
}
else
{
return z;
}

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 << " ";

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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();
}
}

Define a class to represent a bank account. Include the following members:


Data members:
1) Name of the 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.
Write a main program to test the program.

#include<iostream>
#include<string.h>
using namespace std;

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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();
};

void bank::deposit() //depositing an amount


{
int damt1;
cout<<"\n Enter Deposit Amount = ";
cin>>damt1;
bal+=damt1;
}

void bank::withdraw() //withdrawing an amount


{
int wamt1;
cout<<"\n Enter Withdraw Amount = ";
cin>>wamt1;
if(wamt1>bal)
cout<<"\n Cannot Withdraw Amount";
bal-=wamt1;
}
void bank::display() //displaying the details
{
cout<<"\n ----------------------";
cout<<"\n Accout No. : "<<acno;
cout<<"\n Name : "<<nm;
cout<<"\n Account Type : "<<acctype;
cout<<"\n Balance : "<<bal;
}
int main()
{
int acc_no;
char name[100], acc_type[100];

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V


BMS COLLEGE OF ENGINEERING,BANGALORE
DEPT. OF INFORMATION SCIENCE & ENGINEERING
Course : Object Oriented Programming using C++(21IS3PCOOP)

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;
}
}

3rd Sem, BMSCE,ISE, Dr.Shubha Rao V

You might also like