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

OOPS Classes and Objects

Uploaded by

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

OOPS Classes and Objects

Uploaded by

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

Classes and Objects

07/18/2024

OOPs Using C++ 1


OOPS Paradigm and Its Features
C++ was developed by Bjarne Stroustrup at Bell
Laboratories over a period starting in 1979.
Since C++ is an attempt to add object-oriented (OOPs)
features to C (C Successor).
As the language developed, Stroustrup named it as C++
in 1983.

AIM:
OOPs refers to languages that use objects in programming. It aims to implement real-
world entities like inheritance, hiding, polymorphism, etc in programming.

The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
07/18/2024

OOPs Using C++ 2


OOPS Paradigm and Its Features

• Object-oriented programming (OOP) is the key feature which C++ adds to C.

• Basically, the C++ language is the C language with more syntax added. This makes
C++ able to compile all C programs and use C libraries as well.

• OOP enables us to make large programs extremely readable and maintainable by


dividing them into communicating objects.

• This makes C++ a both fast and modern language, however, it's still considered a
difficult one and as one which is used mainly for specific applications.

07/18/2024

OOPs Using C++ 3


Classes and Object

• A class in C++ is the building block that leads to Object-Oriented programming.

• It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.

• A C++ class is like a blueprint for an object.

• An Object is an instance of a Class. When a class is defined, no memory is allocated


but when it is instantiated (i.e. an object is created) memory is allocated.

07/18/2024

OOPs Using C++ 4


Encapsulation

• Encapsulation is defined as wrapping up of data


and information under a single unit.

• In Object Oriented Programming, Encapsulation


is defined as binding together the data and the
functions that manipulates them.

07/18/2024

OOPs Using C++ 5


Encapsulation (Example)
// Program to calculate the area of a rectangle
#include <iostream> int main() {
using namespace std; // Create object of Rectangle class
class Rectangle Rectangle rect(8, 6);
{
// Call getArea() function
public: cout << "Area = " << rect.getArea();
// Variables required for area calculation
int length; return 0;
int breadth; }
// Constructor to initialize variables
Rectangle(int len, int brth) : length(len), breadth(brth) {}
// Function to calculate area
int getArea()
{
return length * breadth;
07/18/2024
}
}; 6
Abstraction

• Abstraction means displaying only essential information and hiding the details.

• Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.

Real Time Example:


Consider a real life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does
not know about how on pressing accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes
etc in the car. This is what abstraction is.

07/18/2024

OOPs Using C++ 7


Abstraction

• Abstraction using Classes: We can implement Abstraction in C++ using classes.


Class helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to outside world and
which is not.

• Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file.
• Whenever we need to calculate power of a number, we simply call the function pow()
present in the math.h header file and pass the numbers as arguments without knowing
the underlying algorithm according to which the function is actually calculating power
of numbers.
07/18/2024

OOPs Using C++ 8


Abstraction using access specifiers:
Access specifiers are the main pillar of implementing abstraction in C++. We can use
access specifiers to enforce restrictions on class members.
#include <iostream>
using namespace std;
class AbstractionExample{ int main(){
private: AbstractionExample obj;
int num; obj.setMyValues(100, 'X');
char ch; obj.getMyValues();
return 0;
public: }
void setMyValues(int n, char c) {
num = n; ch = c;
}
void getMyValues() {
cout<<"Numbers is: "<<num<< endl;
07/18/2024

cout<<"Char
OOPs Using C++ is: "<<ch<<endl; 9
} };
Polymorphism

• The word polymorphism means having many forms.

• The same entity (function or object) behaves differently in different scenarios.

For Example:

A real-life example of polymorphism, a person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an employee. So
the same person posses different behavior in different situations. This is called
polymorphism.

07/18/2024

OOPs Using C++ 10


Inheritance

• Inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically.

• In such way, the developer can reuse, extend or modify the attributes and behaviors
which are defined in other class.
For Example:

07/18/2024

OOPs Using C++ 11


Create a Class
A class in C++ is the building block that leads
to Object-Oriented programming. It is a user-
defined data type, which holds its own data
members and member functions
• To create a class, use the class keyword:
class <Name of the Class>
{
For Example:
//Data Members
//Functions Members
};

07/18/2024

OOPs Using C++ 12


Create a Class
When variables are declared within a class, they are
called attributes or data members.

class <Name of the Class>


{
//access Specifiers
int variable1; //Attributes
};
For Example:

07/18/2024

OOPs Using C++ 13


Creating a Class Object?
• In C++, an object is created from a class.
• We have already created the class named MyFirstClass, so now we can use this to
create objects.
• To create an object of MyFirstClass, specify the class name, followed by the object
name.
For Example:

Creating an object

07/18/2024

OOPs Using C++ 14


Accessing Class Members
• To access the class attributes (variable1), use the dot syntax (.) on the object:
For Example:
<NameofClass>.attribute

Accessing Class Member

Output:
07/18/2024

OOPs Using C++ 15


Access Specifiers or Modifiers

• In the last example,


Why is there an error?
• Members cannot be accessed (or viewed) from outside the class
• So, access specifiers define how the members (attributes and methods) of a
class can be accessed.
• Access specifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding

07/18/2024

OOPs Using C++ 16


Access Specifiers or Modifiers
There are 3 types of access specifiers/modifiers available in C++:
• Public
• Private
• Protected

Note: If we do not specify any access


modifiers for the members inside the
class then by default the access
modifier for the members will
be Private.

07/18/2024

OOPs Usng C++ 17


Access Specifier: Public
1. 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. For Example:

Access Specifier

Output:
07/18/2024

OOPs Using C++ 18


Access Specifier: Private
2. 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 function are allowed to access the private
data members of a class. For Example:

Access Specifier

Output: Error
07/18/2024

OOPs Using C++ 19


Access Specifier: Protected
3. Protected:
Protected access modifier is similar to private access modifier in the sense that it can’t
be accessed outside of it’s class unless with the help of friend class, the difference is that
the class members declared as Protected can be accessed by any subclass (derived class)
of that class as well.

Access Specifier

Output:
07/18/2024

OOPs Using C++ 20


Class Member Functions
There are 2 ways to define a member function:
I. Inside class definition
II. Outside class definition
Inside class definition:
When we define a function inside the class is called inside class definition.
For Example:

07/18/2024

OOPs Using C++ 21


Class Member Functions
Outside class definition:
To define a function outside the class definition,
declare it inside the class and then define it outside of the class. This is done by
specifying the name of the class, followed by the scope resolution :: operator, followed
by the name of the function:
For Example:
class MySecondClass {
public:
void mySecondMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MySecondClass::mySecondMethod() {
cout << "Welcome to C++ Member Functions";
}
07/18/2024

OOPs Using C++ 22


Class Member Functions
For Example:

Output:
07/18/2024

OOPs Using C++ 23


Objects and Memory
• Before using a member of a class, it is necessary to allocate the required 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.

07/18/2024

OOPs Using C++ 24


Objects and Memory

• 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 two objects, namely, obj1, and obj2 of the class Counter have
individual copies of the data member count.

• However, there is only one copy of the member functions setData (), getData () and
inc() that is shared by all the two objects.

07/18/2024

OOPs Using C++ 25


Example:
class Counter int main()
{ {
int count; Counter obj1, obj2;
public: obj1.setData(10);
void setData(int c) obj2.setData(10);
{ cout<<"Object 1 Count\n";
count = c; obj1.inc();
} obj1.getData();
void getData() cout<<"\n";
{ cout<<"Object 2 Count\n";
cout<<"count = "<<count; obj2.getData();
} return 0;
void inc() }
{
count++;
}
}; 07/18/2024

OOPs Using C++ 26


Static Members
• A static member is shared by all the objects of a class.
• All the static data is initialized to 0 when the first object is created. If no other initialization
is done.
• We cant put it in the class definition but it can be initialized outside the class using the
scope resolution operator :: .
• When we declare a member of the class as static it means no matter how many objects of
the class we have created, there is only one copy of the static member. For Example:

07/18/2024

OOPs Using C++ 27


Static Members: Example
class Counter int main()
{ {
static int count; Counter obj1, obj2;
public: obj1.inc();
void printData() obj2.inc();
{ obj2.inc();
cout<<count<<endl; cout<<"Object1 Count: ";
} obj1.printData();
void inc() cout<<"Object2 Count: ";
{ obj2.printData();
count++; }
}
};
int Counter::count=0;
07/18/2024

OOPs Using C++ 28


Guess Output

07/18/2024
?
OOPs Using C++ 29
Output

07/18/2024

OOPs Using C++ 30


Static Object

• Static objects are declared with the keyword static.


• They are initialized only once and stored in the static storage area.
• The static objects are only destroyed when the program terminates i.e. they live
until program termination.

07/18/2024

OOPs Using C++ 31


Static Object Example
class Test void myfunc()
{ {
public: static Test obj;
} // Object obj is still not destroyed because it is static
Test()
{ int main()
std::cout << "Constructor is executed\n"; {
} std::cout << "main() starts\n";
~Test() myfunc(); // Destructor will not be called here
{ std::cout << "main() terminates\n";
return 0;
std::cout << "Destructor is executed\n";
}
}
};

07/18/2024

OOPs Using C++ 32


Guess Output

07/18/2024
?
OOPs Using C++ 33
Output

Output:

07/18/2024

34
Constant Member Function and Object
• A function becomes const when the const keyword is used in the function’s
declaration.
Syntax:
datatype function_name const();
• The idea of const functions is not to allow them to modify the object on which they
are called.
• When a function is declared as const, it can be called on any type of object, const
object as well as non-const objects.

Note: When a function is declared as const, it can be called on any type of object.
Non-const functions can only be called by non-const objects.

07/18/2024

OOPs Using C++ 35


Example: Function without const

class Test { int main()


int value; {
public: Test t;
void putValue1() t.putValue1();
{ cout<<t.getValue();
value = 30; return 0;
} }
int getValue() {return value; }
};

Output:
07/18/2024

OOPs Using C++ 36


const Member Function Example
class Test { int main()
int value; {
public: Test t;
t.putValue2();
cout<<t.getValue();
void putValue2() const return 0;
{ }
value=40;
}
int getValue() {return value; }
};

07/18/2024

37
Guess Output

07/18/2024
?
OOPs Using C++ 38
Output

Why?

• A function becomes const when the const keyword is used in the function’s
declaration.
• The idea of const functions is not to allow them to modify the object on which
they are called.

07/18/2024

39
Example
When a function is declared as const, it can be called on any type of object. Non-const
functions can only be called by non-const objects.

Example:

int main()
class Test {
{
public:
//Constant Object
void print() const
const Test t1;
{
t1.print();
cout<<"Constant Function\n";
//Non-Constant Object
}
Test t2;
};
t2.print();
return 0;
Output:
}
07/18/2024

OOPs Using C++ 40


Friend Function

• 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. A global function can also be declared as friend.
• 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.

• class class_name
• {
• friend data_type function_name(argument/s); // syntax of friend function.
• };

• In the above declaration, the friend function is preceded by the keyword friend. The
function can be defined anywhere in the program like a normal C++ function. The function
definition does not use either the keyword friend or scope resolution operator.
07/18/2024

41
Friend Function
• Characteristics of a Friend function:

• The function is not in the scope of the class to which it has been declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
• It can be declared either in the private or the public part.

07/18/2024

42
Example

#include <iostream> //Global Function


using namespace std;
class XYZ void disp(XYZ obj)
{ {
cout<<obj.num<<endl;
private:
cout<<obj.ch<<endl;
int num=100; }
char ch='Z';
public:
friend void disp(XYZ obj); int main()
}; {
XYZ obj;
disp(obj);
return 0;
07/18/2024 }
43
Friend Class
• A friend class is a class that can access the private and protected members of a class in
which it is declared as friend. This is needed when we want to allow a particular class to
access the private and protected members of a class.
friend class ABC;
};
#include <iostream> class ABC
using namespace std; {
public:
class XYZ { void disp(XYZ obj){
private: cout<<obj.ch<<endl;
char ch='A'; cout<<obj.num<<endl;
}
int num = 11;
};
public: int main()
/* This statement would make class ABC {
* a friend class of XYZ, this means that ABC obj;
* ABC can access the private and protected XYZ obj2;
* members of XYZ class.
07/18/2024 obj.disp(obj2);
*/ return 0;
44
}
Friend Class

• In this example we have two classes XYZ and ABC. The XYZ class has two private data
members ch and num, this class declares ABC as friend class.
• This means that ABC can access the private members of XYZ, the same has been
demonstrated in the example where the function disp() of ABC class accesses the private
members num and ch.
• In this example we are passing object as an argument to the function.

07/18/2024

45
Passing Object as an argument

• Passing object by value to a function creates a shallow local copy of the object in the
function scope. Things you modify here won't be reflected in the object passed to it.
int main() {
#include <bits/stdc++.h>
Example E1, E2, E3; //objects created
using namespace std; // Values are initialized for both objects
class Example { E1.a = 50;
public: E2.a = 100;
int a; E3.a = 0;
cout << "Initial Values \n";
// This function will take object as arguments and return cout << "Value of object 1: " << E1.a
object << ", \nobject 2: " << E2.a
Example add(Example Ea, Example Eb) << ", \nobject 3: " << E3.a
{ << "\n"
Example Ec; E3 = E3.add(E1, E2); // Passing object as an argument to function
Ec.a = Ea.a + Eb.a; add()
// Changed values after passing object as an argument
return Ec; // returning the object
cout << "New values \n";
} };
07/18/2024

46
Passing Object as an argument

• cout << "Value of object 1: " << E1.a


• << ", \nobject 2: " << E2.a
• << ", \nobject 3: " << E3.a
• << "\n";
• return 0;
• }

07/18/2024

47
Passing Object as reference

• This passes a reference to the object to the function. Things you modify here will be
reflected in the object passed to it. No copy of the object is created.
• Declaration #include <bits/stdc++.h>
using namespace std;
• void fun(X &x);
class Example {
• Calling public:
• X x; int a;
• fun(x); // This function will take reference to object as arguments and return
object
Example add(Example &Ea, Example &Eb) // reference of object E1 and
E2 created as Ea and Eb
{
Example Ec;
Ec.a = Ea.a + Eb.a;
Ea.a = Ec.a;
07/18/2024 Eb.a = Ec.a;
return Ec; // returning the object
48
}
Example

int main()
// Passing object as an argument to function add()
{ E3 = E3.add(E1, E2);
Example E1, E2, E3; // Changed values after passing object as an argument
// Values are initialized for both objects cout << "New values \n";
E1.a = 50; cout << "Value of object 1: " << E1.a
E2.a = 100; << ", \nobject 2: " << E2.a
E3.a = 0; << ", \nobject 3: " << E3.a
cout << "Initial Values \n"; << "\n";
cout << "Value of object 1: " << E1.a return 0;
}
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a
<< "\n";
07/18/2024

49
Passing Object as address

• This passes the address of object as a pointer to the function. This is similar to passing
a reference to the object. No copy of object is created.

• Declaration

• void fun(X *x);

• Calling
• X x;
• fun(&x);

07/18/2024

50
Default arguments

• In C++ programming, we can provide default values for function parameters.

• If a function with default arguments is called without passing arguments, then the default
parameters are used.

• However, if arguments are passed while calling the function, the default arguments are
ignored.

07/18/2024

51
Example

07/18/2024

52
Default arguments

• When temp() is called, both the default parameters are used by the function.
• When temp(6) is called, the first argument becomes 6 while the default value is
used for the second parameter.
• When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
• When temp(3.4) is passed, the function behaves in an undesired way because the
second argument cannot be passed without passing the first argument.

• Therefore, 3.4 is passed as the first argument. Since the first argument has been
defined as int, the value that is actually passed is 3.

07/18/2024

53
THANK YOU

07/18/2024

55

You might also like