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

OOPS Notes - Unit-3

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

OOPS Notes - Unit-3

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

Course Name: Object Oriented Programming Systems (OOPS)

Course Code : CS/IT103

Credits: 4

Prepared by: Dr. Rakesh Chowdhury

Assistant Professor (EEE)


Email: [email protected]
UNIT-3: Classes and Objects
Classes and Objects >> Re-visiting Structures in “C” >> Variables and Datatypes

Why we need Arrays???


• Suppose you want to store marks of 150 students, then how you can do it ??
• Sol: by creating 150 variables as shown below ……………… Obviously Not
Classes and Objects >> Re-visiting Structures in “C” >> Arrays

• int a; // variable declaration

• int a[8];

• In most programming languages, an array is


considered a built-in data type, but its size and
elements are user-defined. Arrays are used to
store a collection of same type of data types,
and they provide a way to organize and access
data sequentially.
Classes and Objects >> Re-visiting Structures in “C” >> Arrays
Classes and Objects >> Re-visiting Structures in “C” >> 1D-Arrays

45 63 75 83

19.2 75.3 70.5 83.0

anuj ramya rakesh akshay


Classes and Objects >> Re-visiting Structures in “C” >> 2D-Arrays

45 63 75 83

19.2 75.3 70.5 83.0

anuj ramya rakesh akshay

D B B A
Classes and Objects >> Re-visiting Structures in “C” >> Structures

45 63 75 83

19.2 75.3 70.5 83.0

anuj ramya rakesh akshay

D B B A
Classes and Objects >> Re-visiting Structures in “C” >> Structures

Example: I have a garage and I want to store all the information about a car available in my garage.

Car1

Car2

• Suppose you have 100 cars then storing all information in separate variable is not a good idea as it will
be time consuming and memory consuming.

• Array has the capability to store 100 elements but in this case, it is also not a good option.
Classes and Objects >> Re-visiting Structures in “C” >> Structures

Structure: It is a user defined datatype, that can be used to group elements of different types into a single type

Car1

Car2
Classes and Objects >> Re-visiting Structures in “C” >> Structures

We can access the members of the structure by using dot (.) operator
Classes and Objects >> Re-visiting Structures in “C” >> Structures
Classes and Objects >> Re-visiting Structures in “C” >> Approach

Array or Structure approach ??


In C, the choice between using a structure or an array depends on the nature of the data and the requirements of your
program. Here's a simple example to illustrate when to use a structure or an array:

Example: Storing Student Information

When to use:
•Use a structure when you want to group related data together (e.g., a student's name, age, and grade).
•Use an array when you have a collection of similar data items (e.g., names, ages, or grades of multiple students).
Classes and Objects >> Re-visiting Structures in “C” >> Limitations

Limitations

• The standard C does not allow struct data type to be treated like a built-in type

struct complex
{
float x;
float y;
};

struct complex C1, C2, C3;

• Structures do not permit data hiding.

• Only data members are grouped together.


Classes and Objects >> Defining a CLASS

(a) The idea of Class in C++ is an extension of the idea of Structures in C

(b) A class is a user-defined data type that binds data and functions that operate on data together in a single unit.
The syntax for defining a C++ class is as follows

Access Specifiers
Classes and Objects >> Defining a CLASS

The variables and functions declared within the curly braces are collectively known as members of the class.

The variables declared in the class are known as “data members”

while the functions declared in the class are known as “member functions”.

Example:
Classes and Objects >> Access Specifiers

• The keywords private, public and protected are known as access specifiers (also known as visibility mode). Each
member of a class is associated with an access specifier.

• The access specifier of a member controls its accessibility as well as determines the part of the program that can directly
access the member of the class.

• When a member is declared private, it can be accessed only inside the class,

• When a member is declared private, it is accessible both inside and outside the class.

• Protected members are accessible both inside the class in which they are declared as well as inside the derived classes of
the same class

Note that the default access specifier of the members of a class is private. That is, if no access specifier is provided in
the class definition, the access specifier is considered to be private.

In case of structures, its members are public members.


Classes and Objects >> Access Specifiers >> Public

Public:

All the class members declared under the public specifier will be available
to everyone.

The data members and member functions declared as public can be


accessed by other classes and functions too.

The public members of a class can be accessed from anywhere in the


program using the direct member access operator (.) with the object of that
class.

In the above program, the data member radius is declared as public so it Output
could be accessed outside the class and thus was allowed access from
inside main().
Classes and Objects >> Access Specifiers >> Private

Private:

The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any
object or function outside the class.

Only the member functions or the friend functions are allowed to access the
private data members of the class.

The output of the above program is a compile time error because we are not
allowed to access the private data members of a class directly from outside the
class.
Output

However, we can access the private data members of a class indirectly using the
public member functions of the class.
Classes and Objects >> Access Specifiers >> Private

The third access specifier i.e. Protected is topic in “Inheritance Unit”

Output
Classes and Objects >> Defining an Object

Once a class is defined, it can be used to create variables of its type known as objects. The relation between an object and a
class is the same as that of a variable and its data type. Since an object is an instance of a class, the process of declaring an
object of a class is known as instantiation. The syntax for declaring an object is as follows
Classes and Objects >> Defining Member Functions >> Outside Class

Member functions of a class can be defined either outside the class definition or inside the class definition. In both cases,
the function body remains the same; however, the function header is different

Outside the class Definition:

Member functions of a class that are declared inside a class have to be defined separately outside the class.

return-type class-name : : <function name> (argument declaration)


{
//function body
}

• The membership label <class-name> :: tells the compiler that the function <function name> belongs to <class-name>

• The symbol :: is called scope resolution operator.


Classes and Objects >> Defining Member Functions >> Outside Class

For example, consider the member functions getdata( ) and putdata( ) in earlier slides. They may be coded as follows:

void item : : <getdata (int a , float b)


{
number = a;
cost = b;
}

void item : : <putdata (void)


{
cout<<“Number : “ << number << \n”;
cout<<“Cost : “ << cost << \n”;
}

• Since these functions do not return any value their datatype is void.
• Several different classes can use the same function name. the membership label will resolve their scope.

• Member functions can access private data members of the class.


Classes and Objects >> Defining Member Functions >> Inside Class

Inside the class Definition:

Another way to define a member function is to replace the function declaration by actual function defined inside a class.

class item

{
int number;
float cost;

Public:
void getdata (int a , float b);

void putdata (void);


{
cout<<“Number : “ << number << \n”;
cout<<“Cost : “ << cost << \n”;
}
};
Classes and Objects >> C++ Example with Class

class item //class declaration //two private variables //main program


//two public functions int main ( )
{
int number; //private by default {
float cost; //private by default item x; //object x created
Public:
cout<< “\nobject x” << \n”;
void getdata (int a , float b); //prototype declaration
//function to be defined
x.getdata(100, 299.95) //call member function
//defined outside the class
x.putdata(); //call member function
void putdata (void); //function defined inside the class
{ item y; //another object y created
cout<<“Number : “ << number << \n”;
cout<< “\nobject y” << \n”;
cout<<“Cost : “ << cost << \n”;
}
y.getdata(200, 175.95)
y.putdata();
};
//member function definition
Return 0;
void item : : <getdata (int a , float b) // use membership label
}
{
number = a; //private variables
cost = b; // directly used
}
Classes and Objects >> Making an Outside Function “Inline”

• When a member function is defined inside a class, it is treated like an inline function.
• Therefore, only small functions are defined inside a class.

What is “inline function”


Classes and Objects >> Making an Outside Function “Inline”

class item //class declaration //two private variables


//two public functions
{
int number; //private by default
float cost; //private by default
Public:
void getdata (int a , float b); //prototype declaration
//function to be defined
//defined outside the class
};

//member function definition

inline void item : : getdata (int a , float b) // definition


{
number = a; //private variables
cost = b; // directly used
}
Classes and Objects >> Nesting of Member Functions

• A member function of a class can be called only by an object of that class using dot operator.

• However, A member function can be called by using its name inside another function of the same class.
This is known as nesting of member function.

class set void set : : input (void)


{ {
int m, n; cout << “Input value of m and n are ” << \n;
Public: cin >> m >> n;
void input (void); }
void display(void); void set : : display (void)
int largest (void); {
}; cout << “largest value = ” << \
largest (); //calling member function definition
int set : : largest (void) }
{
if (m >= n) int main ( )
return (m); {
else set A;
return (n); A. input ()
} A. display ()
return 0;
}
Classes and Objects >> Private Member Functions

• It is normal practice to place all the data items in a private section and all the functions public

• Some situation require functions to be hidden. E.g. Deleting an account in customer file, providing increment to
an employee. We can place this functions in private section.

class sample
{
int m;
void read(void);

Public:
void update (void);
void write(void);
};

// if s1 is an object of the class then s1.read ( ) will not work


// objects cannot access private functions.

// however private function can be called by its member function of same class

void sample : : update(void)


{
read ( ); //simple call, no object used
}
Classes and Objects >> Arrays within a Class

• Arrays can be declared as the members of a class.


• The arrays can be declared as private, public or protected members of the class.
• To understand the concept of arrays as members of a class, consider this example.

#include<iostream> void student :: getdata () void main()


const int size=5; { student stu;
cout<<"\nEnter roll no: "; stu.getdata() ;
class student Cin>>roll_no; stu.tot_marks() ;
{ for(int i=0; i<size; i++) getch();
int roll_no; { }
int marks[size]; cout<<"Enter marks in subject"<<(i+1)<<": ";
public: cin>>marks[i] ;
void getdata (); }
void tot_marks ();
}; void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
Classes and Objects >> Array of Objects

• We can have arrays of variables that are of the type class. Such variables are called array of objects.
consider this example.

class employee
• The identifier employee is a user defined datatype and can be used to create
{ objects that relate to different category of the employees.
Char name [30]; employee manager [3]; //array of manager
Float age;
employee foreman [15]; //array of foreman
public: employee worker [75]; //array of worker
void getdata (void);
void putdata(void);
• The array manager contains three objects, namely manager [0], manager
}; [1] and manager [2] of type employee class.

• Similarly foreman array contains 15 objects and worker array contains


75 objects.
Classes and Objects >> Array of Objects

Since array of objects behaves like any other array, we can use the usual array accessing methods to access
individual elements and then the dot operator to access the member functions. For example.

Manager [1]. putdata ( );

this statement will display the data of ith element of array manager. That is this statement requests object manager
[i] to invoke the member function putdata ( )
• An array of object is stored inside the memory in the same way as a multidimensional array.
Classes and Objects >> Array of Objects >> example

class employee const int size = 3;


{ Int main ( )
char name [30]; {
float age; employee manager [size];
public: for (int I = 0; i<size; i++)
void getdata (void); {
void putdata(void); cout << “\nmanager” << i + 1 << “\n”
};
manager[i].putdata ();
Void employee : : getdata (void) }
{ return 0;
cout<< “enter name: “ }
cin >> name;
cout<< “enter age: “
cin >> name;
}
Void employee : : putdata (void)
{
cout<< “Name: “ << name << “\n”;
cout<< “Name: “ << name << “\n”;
}
Classes and Objects >> Array of Objects >> example

Input output

Details of manager 1 manager 1


Enter name: Rakesh Enter name: Rakesh
Enter Age: 31 Enter Age: 31

Details of manager 2 manager 2


Enter name: Rakesh1 Enter name: Rakesh1
Enter Age: 32 Enter Age: 32

Details of manager 3 manager 3


Enter name: Rakesh2 Enter name: Rakesh2
Enter Age: 33 Enter Age: 33
Classes and Objects >> Memory Allocation for objects

• We studied that memory space for objects is allocated when they are declared and not when the class is
specified. This statement is partly true.

• Actually, the member functions are created and placed in the memory space only once when they are defined
as a part of a class specification.

• Since all the objects belonging to that class use the same member functions, no separate space is allocated for
member functions when the objects are created. Only space for member variables is allocated separately for
each object.

• Separate memory allocation for the object are essential because the member variables will hold different data
values for different objects.
Classes and Objects >> Memory Allocation for objects

Common for all objects

Member function 1

Member function 2

Memory created when the functions are defined

Object 1 Object 2 Object 3

Member variable 1 Member variable 1 Member variable 1

Member variable 2 Member variable 2 Member variable 2

Memory created when the objects are defined


Classes and Objects >> Static Data Member

Static data members are class members that are declared using static keywords. A static member has certain
special characteristics which are as follows:
•It is initialized to zero whenever first object of its class is created. No other initialization is permitted.
•For making any data member static we use the keyword “static”
•Only one copy of that member is created for the entire class and is shared by all the objects of that class, no
matter how many objects are created.
•Its lifetime is the entire program.

Object-1 Object-2 Object-3

number number number

Self Question: What is the


Count advantage of static data
Common to all objects member???

• The type and scope of each static member variable must be defined just outside the class definition.
int item : : count; //definition of static data member outside the class
Classes and Objects >> Static Data Member

• This is necessary because, the static data members are stored separately rather than aa a part of object.
• Since they are associated with the class itself rather than any class object, they are also called class variables.
class demo int demo : : z; // need to mention this line
{
int x, y; // normal data members int main ( )
static int z; // static data members {
demo aa, bb;
Public: aa.getdata (5, 10);
void getdata (int a, int b) bb. Getdata (12, 16);
{
x = a; aa.putdata( );
y = b; bb.putdata ();
z = z+1; };
}

void putdata ()
{ Output:
cout<< “x = ” << x << “\n=“ << y << “\n=“ << z;
} x =5 , y = 10, z = 2;
x = 12, y = 16, z = 2;
};
Classes and Objects >> Static Member Function

Like static data member, we can have static member function also. A member function that is declared static has
the following properties;
•A static member function can have access to only other static members (variables or functions).
•A static member function can be called using the class name (instead of its objects) For making any member
function static we use the keyword “static”

class demo static void myfunc ( ) // static member functions


{ {
int x; // data members // cout<< “\ny=” <<x; // not allowed
static int y; // static data members cout<< “\ny=” << y ;
}
Public: };
void getdata (int a) // member functions
{ int demo : : z; // need to mention this line
x = a; int main ( )
y = y+1; {
} demo aa, bb;
aa.getdata (10);
void putdata ( ); aa.putdata ( );
{ // aa. myfunc ( ) // not allowed
cout<< “x = ” << x << “\n=“ << y ; demo : : myfunc ( );
} …………………
}
Classes and Objects >> objects as function arguments

• As we know that, we can pass any type of arguments within the member function and there are any numbers of
arguments.

• In C++ programming language, we can also pass an object as an argument within the member function of class.

• This is useful, when we want to initialize all data members of an object with another object, we can pass objects
and assign the values of supplied object to the current object. For complex or large projects, we need to use
objects as an argument or parameter.
Classes and Objects >> objects as function arguments

#include <iostream> int main()


using namespace std; {
//object declarations
class Demo { Demo d1;
int a; Demo d2;
public: Demo d3;
void set(int x)
{ //assigning values to the data member of objects
a = x;
d1.set(10);
} d2.set(20);
void sum(Demo ob1, Demo ob2)
{ //passing object d1 and d2
a = ob1.a + ob2.a; d3.sum(d1, d2);
}
void print() //printing the values
{ d1.print(); Output:
cout << "Value of A : " << a << endl; d2.print(); Value of A : 10
} d3.print(); Value of A : 20
}; Value of A : 30
return 0;
};
Classes and Objects >> Friend functions

What is a Friend Function ???


Let us take a very simple example to understand the concept of friend function

Class Creation object Creation


class demo int main ( )
To utilize the resources of class
{ {
demo or to access the private
int a, b ;
variables a and b, an object of a
demo obj1 ;
class has the ability to use it with
public: ------------
the help of public member
void getdata ( ); -------------
functions.
}
}

Suppose, there is a function which is not a part of demo class, but still, we want to give it
access the utilize the resources of demo class. This type of function is called as friend
function.
Classes and Objects >> Friend functions

Key Points:
• If a function is defined as a friend function in C++, then the protected and private data of
a class can be accessed using the function.

• By using the keyword friend compiler knows the given function is a friend function.

• For accessing the data, the declaration of a friend function should be done inside the body
of a class starting with the keyword friend.

• A friend function cannot be called using the object of the class. It is called like a normal
function.

• A friend function can use the resources of the class only using an object of the same class.

• When a friend function is called, an object has to be passed as an argument.


Classes and Objects >> Friend functions

class demo int main ( )


{ {
int a, b; demo aa;
aa.getdata ( );
Public: cout << “Sum of a and b is” << sum (aa)
void getdata ( );
friend int sum (demo); return 0;
}; };

void demo : : getdata ( )

{
cout << “enter two numbers”
cin >> a >> b
}

int sum (demo aa)


{
return (aa.a + aa.b)
}
Classes and Objects >> Friend functions

Suppose we have two class, Class A with object x and Class B with object y. If we want to
compare x and y then how we can do that??

void max (A aa, B bb)


class B; class B {
class A { if (aa.x > bb.y)
{ int y; cout << “max is ” << aa.x
int x; else
Public: cout << “max is ” << bb.y
Public: void input ( ) }
void input ( ) { int main ( )
{ cout << “enter no.”; {
cout << “enter no.”; cin >> y; A aa;
cin >> x; } B bb;
} friend void max (A, B); -----------------------------
friend void max (A, B); }; -----------------------------
}; return 0;
};
Classes and Objects >> Friend functions
Classes and Objects >> Friend functions

Question on friend function:

Suppose you are implementing a simple 2D vector class in C++. Define a class
named Vector2D that represents a 2D vector with x and y components. Implement
member functions to perform vector addition, subtraction, scalar multiplication,
and dot product.
Now, to compute the angle between two vectors, you need to access the private x
and y components of both vectors. Implement a friend function named
computeAngle() outside the Vector2D class that takes two Vector2D objects as
parameters and calculates the angle between them.
Ensure to provide necessary validations, such as checking for zero vector, for the
angle calculation.
Classes and Objects >> Friend functions

Question on friend function:


You're tasked with creating a program to manage a library system. Implement a class named
Book to represent a book, which contains private data members for the book's title, author,
and publication year. Include appropriate member functions to set and retrieve these details.
Additionally, implement a class named Library to manage a collection of books. The Library
class should contain a private array to store books and a private variable to keep track of the
number of books in the library. Implement member functions to add a book to the library,
remove a book from the library, and display the details of all books in the library.
Now, suppose you want to find the average publication year of all the books in the library. To
calculate this, implement a friend function named averagePublicationYear() outside the
Library class that takes a Library object as a parameter and returns the average publication
year of all the books.
Ensure to provide necessary validations, such as checking for empty library, for the average
publication year calculation.

You might also like