0% found this document useful (0 votes)
2 views66 pages

Unit 2

The document covers Object Oriented Programming concepts in C++, focusing on classes, objects, access specifiers, and functions. It explains how to create classes and objects, the significance of access specifiers, and various types of functions including function overloading and recursion. Additionally, it discusses advanced topics like inline functions and functions with default arguments, providing examples for better understanding.

Uploaded by

khandujakhanak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views66 pages

Unit 2

The document covers Object Oriented Programming concepts in C++, focusing on classes, objects, access specifiers, and functions. It explains how to create classes and objects, the significance of access specifiers, and various types of functions including function overloading and recursion. Additionally, it discusses advanced topics like inline functions and functions with default arguments, providing examples for better understanding.

Uploaded by

khandujakhanak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GLS UNIVERSITY

242301201 OBJECT ORIENTED PROGRAMMING

UNIT – II
Object Oriented Concepts
Object Oriented Concepts
•Class Structures in C++
• Introduction to Classes and Objects
• Access Specifiers in C++
• Functions and data members in a class
• Functions with Default Arguments
• Inline functions
• Function overloading
• Passing Objects as Function Arguments
• Returning an Object from a Function
• Static Member Data
• Static Member Function
• Constant member functions
• Nested class
C++ Classes/Objects

• C++ is an object-oriented programming language.

• Everything in C++ is associated with classes and objects, along with


its attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such
as drive and brake.

• Attributes and methods are basically variables and functions that


belongs to the class. These are often referred to as "class members".

• A class is a user-defined data type that we can use in our program,


and it works as an object constructor, or a "blueprint" for creating
objects.
Create a Class
To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass
{// The class

public:// Access specifier

int myNum;// Attribute (int variable)


string myString;// A
};
Create a Class


The class keyword is used to create a class called MyClass.


The public keyword is an access specifier, which specifies that
members (attributes and methods) of the class are accessible from
outside the class. You will learn more about access specifiers later.


Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they
are called attributes.


At last, end the class definition with a semicolon ;.
Create an Object


In C++, an object is created from a class. We have already created the
class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by
the object name.

To access the class attributes (myNum and myString), use the dot
syntax (.) on the object:
Create an Object
Access Specifiers


The public keyword is an access specifier. Access specifiers define how
the members (attributes and methods) of a class can be accessed.

public - members are accessible from outside the class

private - members cannot be accessed (or viewed) from outside the
class

protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.

By default, all members of a class are private if you don't specify an
access specifier.
Visibility Modes
Example

class MyClass
{
public:// Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Functions in C++
A function is a group of statements that together perform a
task. Every C++ program has at least one function, which is
main().
If a problem involves lengthy and complex algorithms the
length of the main() may increase to an extent where keeping
track of the steps involved may become difficult task.
In this case if problem is divided into
number of logical units called function.
Each subprogram in C++ is called a function.
A function is a groupof statements that is
given a name, and which can be called from some point of
the program.
Advantages of Functions
You can run one function many times. You can call a
function to execute same lines of code
multiple times without re-writing it.
In case of any modification in the code you can modify only the
function without changing the structure of the program.
Saves thememory space when same code is used
multiple times. Organize the program and divide into number of
subprograms so that seperate module can be used whenever
required.
Development of real life applications needs more than
one programmer when project size is larger.

Project is divided into number of modules among


programmer that builds team work.
Errrors can be easily identified so testing
and debugging becomes easy.
Create a Function


C++ provides some pre-defined functions, such as main(),
which is used to execute code. But you can also create
your own functions to perform certain actions.


To create (often referred to as declare) a function, specify
the name of the function, followed by parentheses ():
Create a Function

Syntax
void myFunction() {
// code to be executed
}

myFunction() is the name of the function

void means that the function does not have a return value.
You will learn more about return values later in the next
chapter.

inside the function (the body), add code that defines what the
function should do
Call a Function


Declared functions are not executed immediately. They are
"saved for later use", and will be executed later, when they
are called.


To call a function, write the function's name followed by two

parentheses () and a semicolon ;


In the following example, myFunction() is used to print a
text (the action), when it is called:
Example

#include <iostream>
using namespace std;
void myFunction()
{
cout << "Hello World!\n";
}
int main()
{
myFunction()
myFunction();
return 0;
}
Function Declaration and Calling

A function declaration tells the compiler about a function's


name, returntype, and parameters.

A function definition provides the actual body of
the function.
Syntax functi on definition:
The first line consists of return_type,
function_name,
parameter list/arguments referred to as function header.


Defining function-1, Declaring function-2
Return Type: A function may return a value. The
return_type is
 the data type of the value the
function returns.
Some functions perform the desired operations
without returning a value. In this case, the
return_type is the keyword void.

Function Name: This is the actual name of the


 function.
The function name and the parameter list together
constitute the function signature.
Parameters are optional; that is, a function

may contain no parameters.
Function Body: The function body contains a
collection of statements that define what the function
does.
Function Declarations:

A function declaration tells the compiler about a function
nameand how to call the function.

The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
 Example:
int max(int num1, int num2);
int max(int, int);
A function doesnot execute by itself, it
is to be invoked by another function

which can be main() or any other function.
A function which invokes another function is called calling
 function and the function which is
invoked is termed as called function.
Calling a Function:
When a program calls a function, program control is transferred to
the called function. A called function performs defined task and
when it’s return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the
main program.
To call a function, you simply need to pass the required parameters
along with function name, and if function returns a value, then you
can store returned value.
Classification of Functions


Functions are categorised into two types:

Built-in functions

User-define functions

Built in functions are those which are already made



available as part of C++ library.
 User defined function is written by the user to solve a
 problem. It gives flexibility in developing the code.
Now we are going to develop our own functions to

accomplish the tasks which we come across.

Functions are classified into four categories:


Classification of Functions


Function with no argument and no return value

Function with no argument but return value

Function with argument but no return value

Function with argument and return value
[Link] with no argument and no return value:This type of
function will not send any data and also not return any data to its calling place
in the program.
2. Function with no argument but return value: This type of function will
send data as arguments but it will not return any kind of data when it will call.
3. Function with argument but no return value:This type of
function will not send any data but it will
return some type of data when it will call. And it will return data to its
calling place from where it is being called in the program
4. Function with argument and return value:This type of function will send
and also return bunch of data toits calling place in the program. From where
it’s being used to call for do something.
Function with no argument and no return value

#include<iostream>
using namespace std;
void sum(){
int no1=5,no2=10,sum;
sum=no1+no2;
cout<<"Sum is :"<<sum;
}
int main(){
sum();
}
Function with no argument but return value

#include<iostream>
using namespace std;
int sum(){
int no1=5,no2=10,sum;
sum=no1+no2;
return sum;
}
int main(){
int result;
result = sum();
cout<<"Sum is "<<result;
}
Function with argument but no return value

#include<iostream>
using namespace std;
void sum(int no1,int no2){
int sum;
sum=no1+no2;
cout<<"Sum is :"<<sum;
}
int main(){
sum(5,8);
}
Function with argument and return value

#include<iostream>
using namespace std;
int sum(int no1,int no2){
int sum;
sum=no1+no2;
return sum;
}
int main(){
int result;
result = sum(5,8);
cout<<"Sum is "<<result;
}
Recursion

A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
Recursion


The recursion continues until some condition is met.


To prevent infinite recursion, if...else statement (or similar
approach) can be used where one branch makes the
recursive call and the other doesn't.
Factorial of a Number Using Recursion
Recursion
Advantages of C++ Recursion


It makes our code shorter and cleaner.


Recursion is required in problems concerning data
structures and advanced algorithms, such as Graph and

Tree Traversal.
Disadvantages of C++ Recursion


It takes a lot of stack space compared to an iterative
program.

It uses more processor time.

It can be more difficult to debug compared to an
equivalent iterative program.
Functions with 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.
Working of default arguments
Functions with Default Arguments

CASE 1 : When temp() is called, both the default parameters are used by
the function.

CASE 2 : When temp(6) is called, the first argument becomes 6 while the
default value is used for the second parameter.

CASE 3 : When temp(6, -2.3) is called, both the default parameters are
overridden, resulting in i = 6 and f = -2.3.

CASE 4 : 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.
Default Argument
The idea behind default argument is very simple.
The idea behind default argument is very simple.
Default Argument
Default value/s are passed to argument/s in function prototype.
A default parameter (also called an optional parameter or a default
argument) is a function parameter that has a default value provided to it.
If the user does not supply a value for this parameter, the default value will
be used.
sum (int x=0,int y); // Incorrect
If you default an argument, then you will have to default all the subsequent
arguments after that.
sum (int x,int y=0);
sum (int x,int y=0,int z); // This is incorrect
sum (int x,int y=10,int z=10);// Correct
You can give any value a default value to argument, compatible with its
datatype.
Functions with Default Arguments
Inline Function

C++ provides an inline functions to reduce the function call


overhead.
When the inline function is called whole code of the inline
function gets inserted or substituted at the point of inline
function call.
This substitution is performed by the C++ compiler at compile
time.
Inline function may increase efficiency if it is small.
Inline Function

C++ inline function is powerful concept that is commonly used with
classes.

If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.

Any change to an inline function could require all clients of the function
to be recompiled because compiler would need to replace all the code
once again otherwise it will continue with old functionality.

To inline a function, place the keyword inline before the function name
and define the function before any calls are made to the function.

The compiler can ignore the inline qualifier in case defined function is
more than a line.

A function definition in a class definition is an inline function definition,
even without the use of the inline specifier.
Inline Function
Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function contains switch or goto statement.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
Inline Function
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
Function Overloding

Function overloading is usually used to enhance the readability of


the program.

If you have to perform one single operation but with different
number or types of arguments, then you can simply overload
the function.

Function overloading can be considered as an example of
polymorphism feature in C++.

By changing number of Arguments.

By having different types of Arguments.
Function Overloding

Now that we know what is parameter list lets see the rules of
overloading: we can have following functions in the same
scope.

sum(int num1, int num2)


sum(int num1, int num2, int num3)
sum(int num1, double num2)

The easiest way to remember this rule is that the parameters
should qualify any one or more of the following conditions,
they should have different type, number or sequence of
parameters.
Function Overloding

For example:
These two functions have different parameter type:

sum(int num1, int num2)

sum(double num1, double num2)

These two have different number of parameters:



sum(int num1, int num2)

sum(int num1, int num2, int num3)
Function Overloding- Example

#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) { Output:
return num1+num2; } 35
int sum(int num1,int num2, int num3) { 191
return num1+num2+num3; }
};
int main() {
Addition obj;
cout<<[Link](20, 15)<<endl;
cout<<[Link](81, 100, 10);
return 0;
}
Function Overloding- Example
#include <iostream>
using namespace std;
class DemoClass {
public:
int demoFunction(int i) {
return i; } Output:
double demoFunction(double d) 100
{ 500.52

return d;
}
};
int main(void) {
DemoClass obj;
cout<<[Link](100)<<endl;
cout<<[Link](5005.516);
return 0;
}
Passing objects as Arguments
The objects of a class can be passed as arguments to
member functions as well as nonmember functions
either by value or by reference.
When an object is passed by value, a copy of the actual
object is created inside the function. This copy is
destroyed when the function terminates.
Passing objects as Arguments
class Demo int main()
{
{ //object declarations
private: Demo d1, d2,d3;
int a; //assigning values to the data member of
objects
public:
[Link](10);
void set(int x) [Link](20);
{
//passing object d1 and d2
a = x;
[Link](d1,d2);
}
void sum(Demo ob1, Demo //printing the values
[Link]();
ob2)
[Link]();
{ [Link]();
a = ob1.a +
return 0;
ob2.a;
}
}
Returning an Object from a function
An object can be returned by a function using
the return keyword.
Returning an Object from a function
Static Member Data


When we define the data member of a class using the static keyword, the
data members are called the static data member.

A static data member is similar to the static member function because the
static data can only be accessed using the static data member or static
member function.

And, all the objects of the class share the same copy of the static
member to access the static data.

Syntax: static data_type data_member;


Static Member Data


Static data members cannot be declared or manipulated by
normal member functions and cannot be accessed directly
through an object of the class.


A static data member is defined with the help of the scope
resolution operator and is defined outside the class.


A static data member in C++ can only be manipulated with the
help of a static member function.


Static data members in C++ are not associated with any object
and can be accessed even without the creation of any object.
Static
#include<iostream>
using namespace std;
class Demo int Demo::count=0;
{ int main()
public: {
static int count; Demo d1,d2,d3;
Demo() cout<<Demo::getcount()
{ ;
count++; }
}
static int getcount()
{
return count;
}
};
Static Member Function


By declaring a function member as static, you make it independent of any
particular object of the class. A static member function can be called even if no
objects of the class exist and the static functions are accessed using only the
class name and the scope resolution operator ::

A static member function can only access static data member, other static
member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to
determine whether some objects of the class have been created or not.
Static Member Function

#include <iostream>
using namespace std;class Demo
{
private:
static int X; public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};//defining
int Demo :: X =10;
int main()
{
Demo X; [Link]();

return 0;
}
Arrays 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.
Constant member functions


The const member functions are the functions which are declared as constant
in the program. The object called by these functions cannot be modified. It is
recommended to use const keyword so that accidental changes to object are
avoided.

A const member function can be called by any type of object. Non-const
functions can be called by non-const objects only.

Here is the syntax of const member function in C++ language,


datatype function_name const();
Constant member functions

#include<iostream>
using namespace std;
class Demo {
int val;
public:
Demo(int x = 0) {
Output:
val = x;
The value using object d : 28
} The value using object d1 : 8
int getValue() const {
return val;
}
};
int main() {
const Demo d(28);
Demo d1(8);
cout << "The value using object d : " <<
[Link]();
cout << "\nThe value using object d1 : " <<
[Link]();
return 0;
}
Nested Class

A nested class is a class that is declared in another class. The nested class is also a
member variable of the enclosing class and has the same access rights as the other
members. However, the member functions of the enclosing class have no special access
to the members of a nested class.

Syntax for accessign inner class :

OuterClassName::NestedClassName objectName;
Nested Class
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n; OUTPUT:
} Nested classes in C++
void putdata() { The number is 9
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
[Link](9);
[Link]();
return 0;

You might also like