Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views84 pages

Unit I C

Uploaded by

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

Unit I C

Uploaded by

sambodhjain33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

CSE2PR01A Object Oriented

Concepts using C++

Department of Computer Engineering and


Technology

7/2/2024 Object Oriented Concepts using C++ 1


Unit I Introduction to OOP

7/2/2024 Object Oriented Concepts using C++ 2


Software Evolution

1,0

Machine Language
Assembly Language
Procedure - Oriented
Object Oriented Programming

7/2/2024 Object Oriented Concepts using C++ 3


Procedural Programming

Main Program

Function-1 Function-2 Function-3

Function-4 Function-5

Function-6 Function-7 Function-8

7/2/2024 Object Oriented Concepts using C++ 4


• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to
function.
• Functions transform data from one form to another.
• Employs top-down approach in program design
5
Object Oriented Programming
• Design methodology for creating a non-rigid application
• Works on entity called as objects
• Decompose problem in to small unit of work which are accessed via Objects.
Object B
• Emphasis is on data rather than procedure.
• Data is hidden and cannot be accessed by external function. Data
• Objects may communicate with each other through function.
• Follows bottom up approach in program design. Function

Object A

Data Object C

Data
Function

Function
7/2/2024 Object Oriented Concepts using C++ 6
Features of OOP
• Programming language with OOP support has to fulfill these
features
– Abstraction
– Encapsulation
– Inheritance
– Polymorphism

7/2/2024 Object Oriented Concepts using C++ 7


Real life Example
• Mobile as an object was designed to provide basic functionality as
– Calling and Receiving calls
– Messaging
• Thousands of new features and models are getting added

Mobile

iPhone Samsung Nokia

7/2/2024 Object Oriented Concepts using C++ 8


Objects
• Any real world entity which can have some characteristics or which can
perform some work.
– an instance i.e. - a copy of an entity in programming language.
• A mobile manufacturing company, at a time manufactures lacs of pieces
of each model which are actually an instance.
– objects are differentiated from each other via some identity (e.g.
IMEI number) or its characteristics.

Mobile mbl1 ;
Mobile mbl2 ;
7/2/2024 Object Oriented Concepts using C++ 9
Class
class Mobile
{
private:
string IMEICode, SIMCard, Processor;
Mobile int InternalMemory;
Class
bool IsSingleSIM;
public:
Properties
void GetIMEICode() {
Processor cout << "IMEI Code - IEDF34343435235";
IMEICode }
IsSingleSIM void Dial() {
Methods cout << "Dial a number";
}
Dial void Receive() {
Receive
cout << "Receive a call";
SendMessage
GetWifiConnection }
ConnectBlueTooth void SendMessage(){
GetIMEICode cout << "Message Sent";
}
7/2/2024 Object Oriented Concepts using C++ 10
}
● A Class is a plan which describes the object.
○ We call it as a blue print of how the object should be represented.
● Mainly a class would consist of a name, attributes & operations.
● A Mobile can be a class which has some attributes like Profile Type, IMEI Number,
Processor, etc. & operations like Dial, Receive & SendMessage.

11
Abstraction
• Abstraction - only show relevant details and rest all hidden
– its most important pillar in OOPS as it is providing us the technique to
hide irrelevant details from User
• Dialing a number calls some method internally which concatenate the
numbers and displays it on screen but what is it doing we don’t know.
• Clicking on green button actual send signals to calling person’s mobile
but we are unaware of how it is doing.
void Dial()
{
//Write the logic
cout << "Dial a number";
7/2/2024
} Object Oriented Concepts using C++ 12
Encapsulation
• Encapsulation is defined as the process of enclosing one or more details from
outside world through access right.
– It specifies how much access should be given.
• Both Abstraction & Encapsulation works hand in hand because Abstraction
says what details to be made visible & Encapsulation provides the level of
access right to that visible details. i.e. – It implements the desired level of
abstraction.

private:
string IMEICode = "76567556757656";

7/2/2024 Object Oriented Concepts using C++ 13


Polymorphism
class Samsumg :public Mobile
• Polymorphism
{ can be defined as the ability of doing the same operation
butpublic:
with different type of input.
void GetWIFIConnection() {
– More preciselyconnected";
cout<<"WIFI we say it as ‘many forms of single entity’
• } or Compile time polymorphism
Static
//This is one method which shows camera functionality
• Compile time polymorphism
void CameraClick() { the compiler knows which overloaded
method cout<<“Camera
it is goingclicked";
to call.
}
//overloaded method which shows camera functionality as well but with panaroma mode
void CameraClick(string CameraMode) {
cout<<"Camera clicked in " + CameraMode + " Mode";
}
}

7/2/2024 Object Oriented Concepts using C++ 14


Polymorphism
• Dynamic polymorphism or Runtime polymorphism
• Method Overriding is used to implement dynamic
polymorphism
• By runtime polymorphism, we can point to any derived class
from the object of the base class at runtime that shows the
ability of runtime binding.

7/2/2024 Object Oriented Concepts using C++ 15


Inheritance
• Ability to extend the functionality from base entity to new entity
belonging to same group.
– This will help us to reuse the functionality which is defined before.
• There are mainly 4 types of inheritance:
– Single level inheritance
– Multi-level inheritance Mobile
– Hierarchical inheritance
iPhone Samsung Nokia
– Hybrid inheritance
Samsung Nokia
– Multiple inheritance iPhone 5
S4 Lumia 625

Samsung
iPhone 6
S5

7/2/2024 Object Oriented Concepts using C++ iPhone X 16


Object based Vs Oriented Language
• objects-based programming are • Object-oriented programming language
languages that support incorporates two additional features,
programming with objects namely, inheritance and dynamic binding
• Feature that are required for • Feature that are required for object-
object- based programming are: oriented programming are:
– Data encapsulation – Data encapsulation
– Data hiding and access mechanisms
– Data hiding and access mechanisms
– Automatic initialization and clear-up of objects
– Automatic initialization and clear-up
– Operator overloading
of objects
– Inheritance
– Operator overloading
– dynamic binding
• E.g. Visual Basic
7/2/2024 Object Oriented Concepts using C++ 19
Benefits of OOP

• We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving
of development time and higher productivity,
• It is very easy to partition the work in a project based on objects.
• OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time).
• The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
• OOP systems can be easily upgraded from small to large systems.
• It is possible to map the objects in problem domain to those in the program.
• The principle of data hiding helps the programmer to build secure programs which
cannot be invaded by the code in other parts of the program.
• By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
• The data-centered design approach enables us to capture more details of model in an
implementable
7/2/2024 form. Object Oriented Concepts using C++ 20
Application of OOP
• Real-business system are often complex and contain many objects
with complicated attributes and methods.
• Some of the areas of application of OOPs are:
– Real-time system
– Simulation and modeling
– Object-oriented data bases
– AI and expert systems
– Neural networks and parallel programming
– Decision support and office automation systems
– CAD/CAM systems
7/2/2024 Object Oriented Concepts using C++ 21
Introduction to C++ ?
• C++ is a versatile language for handling very large programs
including editors, compilers, databases, communication
systems and any complex real-life applications
– C++ allows create hierarchy related objects to build special object-
oriented libraries which can be used later by many programmers.
– the C part of C++ gives the language the ability to get close to the
machine-level details.
– C++ programs are easily maintainable and expandable

7/2/2024 Object Oriented Concepts using C++ 22


BASICS OF C++

7/2/2024 Object Oriented Concepts using C++ 23


Simple C++ Program
// Simple C++ program to display "Hello World"
// Header file for input output functions
instructs the compiler to include the contents of the file enclosed
#include<iostream>
within angular brackets into the source file.
defines a scope for the identifiers that are used in a program
using namespace std;

// main function - where the execution of program begins


int main()
{
// prints hello world
cout<<"Hello World";
every main() returns an integer value to operating system
return 0;
and therefore it should end with return (0) statement
}

7/2/2024 Object Oriented Concepts using C++ 24


Structure of C++ Program
Include File
• It is a common practice to organize a program into
three separate files Class Declaration
Serv
• The class declarations are placed in a header file and Member Functions er
the definitions of member functions go into another Member Function
Definitions
file. Main Function Program
Class Definition
• The main program that uses the class is placed in a
third file which “includes” the previous two files as Main function program
well as any other file required Clie
nt

7/2/2024 Object Oriented Concepts using C++ 25


C/C++ Compilation and Linking

Source code file


(program.c)

Preprocessor

Expanded source code


(program.i)
Compiler

Object Code
(program.obj)
Linker

Executable file
(program.exe)

7/2/2024 Object Oriented Concepts using C++ 26


FUNCTION in C++
• Function is a collection of declarations and statements
• A function must be defined prior to it’s use in the program

Type name_of_the_function (argument list)


{
//body of the function
}

7/2/2024 Object Oriented Concepts using C++ 27


C++ Function Definition
• C++ function is defined in two steps (preferably but not
mandatory)
– Step #1 – declare the function signature in either a header file (.h file)
or before the main function of the program
– Step #2 – Implement the function in either an implementation file
(.cpp) or after the main function

28
7/2/2024 Object Oriented Concepts using C++
The Syntactic Structure of a C++ Function

• A C++ function consists of two parts


– The function header, and
– The function body
• The function header has the following syntax

<return value> <name> (<parameter list>)

• The function body is simply a C++ code enclosed between { }


29
7/2/2024 Object Oriented Concepts using C++
Example of User-defined
C++ Function

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

30
7/2/2024 Object Oriented Concepts using C++
Example of User-defined
C++ Function
Function header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

31
7/2/2024 Object Oriented Concepts using C++
Example of User-defined
C++ Function
Function header Function body

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

32
7/2/2024 Object Oriented Concepts using C++
Function Signature
• The function signature is actually similar to the function header
except in two aspects:
– The parameters’ names may not be specified in the function
signature
– The function signature must end with a semicolon
• Example Unnamed Semicolon
Parameter ;

double computeTaxes(double) ;

7/2/2024 Object Oriented Concepts using C++ 33


Why Do We Need Function Signature?
• For Information Hiding
– If you want to create your own library and share it with your
customers without letting them know the implementation details,
you should declare all the function signatures in a header (.h) file and
distribute the binary code of the implementation file
• For Function Abstraction
– By only sharing the function signatures, we have the liberty to change
the implementation details from time to time to
• Improve function performance
• make the customers focus on the purpose of the function, not its
implementation

34
7/2/2024 Object Oriented Concepts using C++
Example
#include <iostream> double computeTaxes(double income){
#include <string> if (income<5000) return 0.0;
using namespace std; return 0.07*(income-5000.0);
// Function Signature }
double getIncome(string); double getIncome(string prompt){
double computeTaxes(double); cout << prompt;
void printTaxes(double); double income;
void main() cin >> income;
{ return income;
// Get the income; }
double income = getIncome("Please enter the employee void printTaxes(double taxes){
income: "); cout << "The taxes is $" << taxes << endl;
// Compute Taxes }
double taxes = computeTaxes(income);
// Print employee taxes
printTaxes(taxes);
} 35
7/2/2024 Object Oriented Concepts using C++
Default Arguments in Function
// C++ Program to demonstrate working of default
Case 1: No argument passed Case 2: First argument passed argument
void temp (int = 10, float = 8.8); void temp (int = 10, float = 8.8); #include <iostream>
int main() { int main() { using namespace std;
temp(); temp(6); void display(char = '*', int = 1);
} } int main()
void temp(int i, float f) { void temp(int i, float f) { {
……… ……… cout << "No argument passed:\n";
} } display();
cout << "\nFirst argument passed:\n";
Case 4: Second argument passed display('#');
Case 3: All arguments passed cout << "\nBoth argument passed:\n";
void temp (int = 10, float = 8.8);
void temp (int = 10, float = 8.8); int main() { display('$', 5);
int main() { return 0;
temp(3.4);
temp(6, -2.3); }
}
} void display(char c, int n) {
void temp(int i, float f) {
void temp(int i, float f) { for(int i = 1; i <= n; ++i) {
………
……… cout << c;
}
} i = 3, f=8.8 }
7/2/2024 Object Oriented Concepts using C++ 36
Because, only the second argument cannot be passed. The cout << endl;
parameter will be passed as the first argument.
• In C++ programming, you can provide default values for
function parameters.
• The idea behind default argument is simple. If a function is
called by passing argument/s, those arguments are used by the
function.But if the argument/s are not passed while invoking a
function then, the default values are used.
• Default value/s are passed to argument/s in the function
prototype.

37
Reference Variables
• A reference is an alias, or an alternate name to an existing variable
int x = 5;
int &z = x;// z is another name for x

– Must
intbe &z
initialized
; when it is declared reference must be initialized
//Error:

• References acts as function formal parameters to support pass-by-reference


• Any changes to reference variable inside the function are reflected outside
the function
7/2/2024 Object Oriented Concepts using C++ 38
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{ void main()
int x = 4; // Local variable {
4? x
fun(x); 1 int x = 4;
fun(x);
cout << x << endl; cout << x << endl;
} 7/2/2024
39 Object Oriented Concepts using C++
}
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y)
} {
3 cout<<y<<endl;
void main() y=y+5;
{ }
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 4? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 40
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y )
} {
cout<<y<<endl;
void main() 4 y=y+5; 9
{ }
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 4? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 41
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y )
} {
cout<<y<<endl;
void main() y=y+5;
{ 5
}
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 9? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 42
Classes and Objects

7/2/2024 Object Oriented Concepts using C++ 43


Class
• A way to bind data and associated function together
• An expanded concept of a data structure, instead of holding
only data, it can hold both data and function.
• The data is to be hidden from external use.

7/2/2024 Object Oriented Concepts using C++ 44


Class

keyword
class class_name
{ data member
private:
variable declaration;
body
public:
function declaration; member
…. function
} ; access
7/2/2024
specifiers
Object Oriented Concepts using C++ 45
Access Specifiers
Less Restrictive
Clas
Accessible from own class s
Private Area
public Accessible from derived class
No entry to Data
Accessible from class objects
Private
area Functions
Accessible from own class
protected
Accessible from derived class
Data
Entry allowed
to
Functions
Public area
private Accessible from own class Public Area

More Restrictive
7/2/2024 * By default all items defined in the class are private 46
Object Oriented Concepts using C++
Access Specifiers
Employee
Department Manager
public:
string name;
protected:
string designation;
private:
int Age;

CommissionEmployee

SalariedEmployee

7/2/2024 Object Oriented Concepts using C++ 47


Access Specifiers

class Person {
public: //access control
string firstName; //these data members
string lastName; //can be accessed
int dateOfBirth; //from anywhere
private:
string address; // can be accessed inside the class
long int insuranceNumber; //and by friend classes/functions
protected:
string phoneNumber; // can be accessed inside this class,
int salary; // by friend functions/classes and derived classes

};
7/2/2024 Object Oriented Concepts using C++ 48
Objects
• A class provides the blueprints for objects, so basically an
object is created from a class.
• Objects of#include
a class are declared with exactly the same sort of
<iostream>
declaration asnamespace
using variablesstd; of basic types
class Box {
public:
Class double length; // Length of a box
double breadth; // Breadth of a box Public data members
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box Objects of Box class
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
7/2/2024 } Object Oriented Concepts using C++ 49
Objects
int main() {
Box Box1; // Declare Box1 of type Box
• The objects of class will have their Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
own copy of data members. // box 1 specification
• The public data members of Box1.height = 5.0;
Box1.length = 6.0;
Access data members
of Box1 object
objects of a class can be accessed Box1.breadth = 7.0;

using the direct member access // box 2 specification


Box2.height = 10.0; Access data
operator (.) Box2.length = 12.0; members
Box2.breadth = 13.0;
of Box2 object
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
7/2/2024
return 0;
Object Oriented Concepts using C++ 50
}
"

Member class
Functions
Box {
public:
double length, breadth, height;
• Can be defined inside class double getVolume(void) { // Returns box volume
return length * breadth * height; Inline function
return_type function_name (parameters) }
{ double getSurfaceArea(void); // returns surface area
// function body };
} // member function definition member function declaration
• Or outside the class double Box::getSurfaceArea(void) {
….
return_type class_name::function_name (formal} parameters) member function definition
{ int main() { outside class
// function body Box Box1;
} Box1.length = 10;
accessing member functions
• Functions defined inside class are Box1.height = 20;
Box1.breadth=30;
treated as inline functions by cout << “Volume of box: “ << Box1.getVolume() << endl;
compiler cout << “Surface Area of box: “ << Box1.getSurfaceArea() <<
endl;
7/2/2024 Object Oriented }Concepts using C++ 51
Array of Objects
#include <iostream> int main()
#include <string> {
using namespace std; Student st[5];
class Student for( int i=0; i<5; i++ )
{ {
string name; cout << "Student " << i + 1 << endl;
int marks;
cout << "Enter name" << endl;
public:
void setName() st[i].setName();
{ cout << "Enter marks" << endl;
cin>>name; st[i].setMarks();
} }
void setMarks()
{
for( int i=0; i<5; i++ )
cin >> marks;
} {
void displayInfo() cout << "Student " << i + 1 << endl;
{ st[i].displayInfo();
cout << "Name : " << name << endl; }
cout << "Marks : " << marks << endl; return 0;
} }
};

7/2/2024 Object Oriented Concepts using C++ 52


Inline functions
• On function call instruction, CPU stores the memory address of
instruction following the function call
• CPU then transfers the control to callee function
• CPU executes callee function, stores function return value at
predefined memory location/register and returns control back
to caller
• It becomes an overhead if execution time of function is less
than switching time for caller function

7/2/2024 Object Oriented Concepts using C++ 53


Inline functions
Mymaths.cpp

int AddNumbers(int x, int y){


main.cpp int z; PROLOG
z = x + y;
int main() { save regs
return z; EPILOG
int x = 20; pass args }
int y = 10;
inline int SubtractNumbers (int x, int y) {
cout << “Sum of Numbers: “ << AddNumbers(x, y) << endl; call AddNumbers int z;
cout << “Difference between Numbers: “ << SubtractNumbers(x, y) <<z endl;
= x – y; z = x – y;
cout << “Multiplication of numbers: “ << MultiplyNumbers(x, y) << endl;
restore regs return z;
}
}
int MultiplyNumbers (int x, int y) {
int z;
z = x * y;
return z;
}

7/2/2024 Object Oriented Concepts using C++ 54


Inline Functions
• Inline functions reduce the call overhead.
• Inline functions gets expanded when called
– i.e. when inline function is called, entire code of inline function is
inserted/substituted at point of inline function call
– The substitution is performed by compiler at compile time
inline return-type function-name(parameters)
{
// function code
}

• By default compiler treats class methods defined under class as inline


functions
7/2/2024 Object Oriented Concepts using C++ 55
class Employee {
static int EmployeeId; Static Data Members
public:
int getEmpId (void) {
return ++EmployeeId;
• Dat
}
void addEmployee(str);
}; Employee
void Employee::addEmployee(str name) { EmployeeId= 102
newId = getEmpId();
cout << “Added New Empl ” <<name <<“ with Id: “<<
newId <<endl;
…. Emp_A Emp_B
} EmployeeId=1 EmployeeId=2
int Employee::EmployeeId
int main() {
Employee Emp_A, Emp_B;
Emp_A.addEmployee(“Amit”);
Emp_B.addEmployee(“Bijoy”);
} # a.out
Added New Empl Amit with Id: 1
7/2/2024 Added
Object Oriented New
Concepts using Empl
C++ Bijoy with Id: 2 56
• a members of the class which are shared by all objects are known as static
data members.
• Only one copy of static variable is maintained by the class and it is common
for all objects.
• Static members are declared inside the class and defined outside the class.
• It is initialized to zero when the first object of its class is created.
• You cannot initialize a static member variable inside the class declareation.
• It is visible only within the class but its lifetime is the entire program.
• Static members are generally used to maintain values common to the
entire class.
57
Static Member Function in C++

Static Member Function in a class is the function that is declared as


static because of which function attains certain properties as defined
below:
• A static member function is independent of any object of the class.
• A static member function can be called even if no objects of the
class exist.
• A static member function can also be accessed using the class name
through the scope resolution operator.
• A static member function can access static data members and static
member functions inside or outside of the class.
• You can use a static member function to determine how many
objects of the class have been created.
7/2/2024 Object Oriented Concepts using C++ 58
Static Member Function in C++

7/2/2024 Object Oriented Concepts using C++ 59


Constructors
• A constructor is a special member function that is a member of a class and has same
name as that of class.
• It is used to initialize the object of the class type with a legal initial value.
• It is called constructor because it constructs the values of data members of the
class. Class
{
A
Default Values
int a;
float b; a 0 0 10
char ch;
String str; b 0.0 0.0 20.0
boolean bl;

A() ch One Space m


{
a=10; str null null java
b=20.0;
ch=‘m’;
str=“java” bl false false true
bl=true
}
}

7/2/2024 Object Oriented Concepts using C++ 60


Constructor - Declaration
• For the T class:
T(args); // inside class definition
or T::T(args); // outside class definition
class X {
int i ;
public:
int j,k ;
X() {
i = j = k =0; Inside class
}
};
X::X()
{
i = j = k =0; Outside class
}

7/2/2024 Object Oriented Concepts using C++ 61


Constructor - Properties
• Automatically called when an object is created
Name same as Class name • We can define our own constructors
• They can not be inherited.
class X {
int i ; • These cannot be static.
public: Under public section
int j,k ; • Overloading of constructors is possible
X() {
i=j=k
• Constructors can have default argument as
=0; other C++ functions.
}
}; • If you do not specify a constructor, the compiler
Does not return anything. Not generates a default constructor for you (expects
even void no parameters and has an empty body).
• Default and copy constructor are generated by
the compiler whenever required.
7/2/2024 Object Oriented Concepts using C++ 62
Types of Constructors
• There are several forms in which a constructor can take its shape, namely

Constructors
Default
Default Parametrized Copy
Parametrized
Constructor Constructor Constructor
Constructor

7/2/2024 Object Oriented Concepts using C++ 63


Default Constructor
• This constructor has no argument in it
• Compiler creates one, if not explicitly defined
• Default Constructor is also called as no argument constructor

class rectangle{ int main()


private: {
float height; rectangle rect;
float width; }
public:
rectangle(){ # a.out
cout <<“creating rectangle object”; creating rectangle object
}
};

7/2/2024 Object Oriented Concepts using C++ 64


Parameterized Constructors
• A parameterized constructor is just one that has parameters specified in it.
• We can pass the arguments to constructor function when object is created.
• A constructor that can take arguments are called parameterized constructors

class rectangle{ int main()


private: {
float height; rectangle book(10.0, 20.0); //implicit call
float width; rectangle box = rectangle(20.0,30.0) //explicit call
public: rectangle eraser= rectangle(25.0, 35.0)
rectangle(float h, float w){ }
height=h;
width=w;
}
};
7/2/2024 Object Oriented Concepts using C++ 65
Default Parametrized Constructors
• Default argument is an argument to a function that a programmer is not required to specify.
• C++ allow the programmer to specify default arguments that always have a value, even if one is not
specified when calling the funtion
e.g. int power(int a, int b=2);
• The programmer may call this function in two ways
result = power(10,3); // result = 103 = 1000
result = power(10); // result = 102 = 100
• On similar lines, it is possible to define constructors with default parameters
rectangle(float h=1.0, float w=2.0)
and hence these are valid call statements
rectangle book(10.0, 20.0); // results into book object with height=10, width=20
rectangle box(10.0); // results into box object with height=10, width=2

7/2/2024 Object Oriented Concepts using C++ 66


Example of default and default parameterized
constructor
class rectangle{ void main()
private: {
float height; rectangle book(); //implicit call of default constructor
float width; rectangle box(20.0); //implicit call of default
public: parametrized constructor
rectangle eraser(10.0, 20.0); // explicit call of default
rectangle(float h, float w); parametrized constructor
rectangle(){ rectangle sharpener = rectangle(10);
height=width=1.0; rectangle geometry_box = rectangle(50.0,70.0);
} rectangle paper = rectangle (3.0, 6.0);
rectangle(float h, float w=5.0){ rectangle calculator = rectangle (15.0, 25.0) //explicit call
for existing object
height = h; }
width = w;
}
};7/2/2024 Object Oriented Concepts using C++ 67
Copy Constructor
• Copy
class constructor is used to declare and initialize an object
rectangle{
private:
from another object
float height; int main()
float width;
• If you have
public:
not defined a copy constructor,
{ the complier
rectangle book_1(10.0, 20.0);
automatically creates
rectangle(float h, floatitw);
and it is public rectangle book_2(book_1);
}
• Copy constructor
rectangle(float h, float w){ always takes argument as a reference object.
height=h; This would define the book_2 object and at
• Thewidth=w;
process of initializing through a copy constructor
the same time initialize it to theis known
value of
book_1. i.e. height and width of book_2
}
as copy initialization.
rectangle(rectangle &p){
object would be 10 and 20 respectively

height = p.height;
width = p.width;
}
};7/2/2024 Object Oriented Concepts using C++ 68
Constructor Overloading
• You can have more than one constructor in a class, as long as each has a different list
of arguments
class rectangle{
private:
float height;
float width;
public:
rectangle(){
height=width=10.0;
}
rectangle(float h, float w){
height=h;
width=w;
}
7/2/2024 }; Object Oriented Concepts using C++ 69
Destructors
• A destructor is used to destroy the objects that have been created by a constructor.
• Like constructor, the destructor is a member function whose name is the same as
the class name but is preceded by a tilde.
~T();
• It is a good practice to declare destructors in a program since it releases memory
space for further use.

7/2/2024 Object Oriented Concepts using C++ 70


Destructors
• It is a special member function of a class, which is used to destroy the memory of
object
• Its name is same as class name but tilde sign preceding destructor
• It must be declared in public section
• It does not return any value; not even void
• It can be defined inline/offline
• Does not need to call because it gets call automatically whenever object is
destroyed from its scope
• It can be called explicitly also using delete operator
• It does not take parameters
• Destructor cannot be overloaded nor inherited.
7/2/2024 Object Oriented Concepts using C++ 71
Destructors
int count=0; int main() #a.out
class rectangle { enter main
{ cout<<"\n enter main"; Created ObjectId:1
public: rectangle a1,a2,a3,a4; Created ObjectId:2
rectangle(){ { Created ObjectId:3
count++; cout<<"\nEnter block1"; Created ObjectId:4
cout<<"\n Created ObjectId:"<<count; rectangle a5; Enter block1
} } Created ObjectId:5
~rectangle() { { Destroyed ObjectId:5
cout<<"\n Destroyed ObjectId:"<<count; cout<<"\nEnter block2"; Enter block2
count--; rectangle A6; Created ObjectId:5
} } Destroyed ObjectId:5
}; cout<<"\nRe-enter main"; Re-enter main
return 0; Destroyed ObjectId:4
} Destroyed ObjectId:3
Destroyed ObjectId:2
Destroyed ObjectId:1
7/2/2024 Object Oriented Concepts using C++ 72
Memory Allocation
• It is important to understand that compiler allocates memory to objects sequentially
and destroys in reverse order. This is because C++ compiler uses the concept of stack
in memory allocation and de-allocation
eraser

box
book

eraser

De-allocation
Allocation

box

book

7/2/2024 Object Oriented Concepts using C++ 73


Dynamic memory allocation
• Dynamic memory allocation in C/C++ refers to performing
memory allocation at run time as per the program requirement
• Dynamically allocated memory is allocated on Heap and non-
static and local variables get memory allocated on Stack
• Memory in C++ program is divided into two parts −
– The stack − All variables declared inside the function will take up
memory from the stack.
– The heap − This is unused memory of the program and can be used
to allocate the memory dynamically when program runs.
7/2/2024 Object Oriented Concepts using C++ 74
Applications of Dynamic memory allocation

• To allocate memory of variable size which is not possible with


compiler allocated memory
• The most important use is flexibility provided to programmers.
We are free to allocate and deallocate memory whenever we
need and whenever we don’t need anymore. There are many
cases where this flexibility helps. Examples of such cases are
Linked List, Tree, etc

7/2/2024 Object Oriented Concepts using C++ 75


new and delete Operators

pointer-variable = new data-type;


• The new operator denotes a request for memory allocation on
// Pointer initialized with NULL
// Then request memory for the variable
the Heap int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;

Initialize memory:
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);

7/2/2024 Object Oriented Concepts using C++ 76


Pointers and Dynamic Memory

Here are the steps:

int * myIntPtr; // create an integer pointer variable


myIntPtr = new int; // create a dynamic variable of the size integer

new returns a pointer (or memory address) to the location where the
data is to be stored.

7/2/2024 Object Oriented Concepts using C++ 77


Pointers and Dynamic Memory

Free Store (heap)

int * myIntPtr
myIntPtr = new int;

myIntPtr

7/2/2024 Object Oriented Concepts using C++ 78


Pointers and Dynamic Memory

Free Store (heap) Use pointer variable

12 3
int * myIntPtr
myIntPtr = new int;
myIntPtr

*myIntPtr = 123;

7/2/2024 Object Oriented Concepts using C++ 79


Pointers and Dynamic Memory

• We can also allocate entire arrays with the new operator.


These are called dynamic arrays.

• This allows a program to ask for just the amount of


memory space it needs at run time.

7/2/2024 Object Oriented Concepts using C++ 80


Pointers and Dynamic Memory
Free Store (heap)

0 int * myIntPtr;
myIntPtr myIntPtr = new int[4];
1 3 2 5
2
3 myIntPtr[1] = 325;

Notice that the pointer symbol is


understood, no * is used to reference
the array element.

7/2/2024 Object Oriented Concepts using C++ 81


Pointers and Dynamic Memory

The new operator gets memory from the free store (heap).

When you are done using a memory location, it is your responsibility


to return the space to the free store. This is done with the delete
operator.

delete myIntPtr; // Deletes the memory pointed


delete [ ] arrayPtr; // to but not the pointer variable

7/2/2024 Object Oriented Concepts using C++ 82


Pointers and Dynamic Memory

Dynamic memory allocation provides a more flexible solution when


memory requirements vary greatly.

The memory pool for dynamic memory allocation is larger than that
set aside for static memory allocation.

Dynamic memory can be returned to the free store and allocated for
storing other data at later points in a program. (reused)

7/2/2024 Object Oriented Concepts using C++ 83


Example of Dynamic Arrays
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" Output
<<endl; Constructor called!
} Constructor called!
~Box() { Constructor called!
cout << "Destructor called!" Constructor called!
<<endl; Destructor called!
} Destructor called!
}; Destructor called!
int main() { Destructor called!
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete
array
return 0;
7/2/2024
} Object Oriented Concepts using C++ 84
}
Friend Functions/Classes
• friends allow functions/classes access to private data of other classes.
• Friend functions
– A 'friend' function has access to all private and protected members (variables
and functions) of the class for which it is a 'friend'.
– friend function is not the actual member of the class.
– To declare a 'friend' function, include its prototype within the class, preceding it
with the C++ keyword 'friend'.

7/2/2024 Object Oriented Concepts using C++ 85


Example
class Employee
{
class Employee class Boss
private:
{ string name; {
private: double salary; public:
stringvoid
friend name;
raiseSalary(double a, Employee &e); Boss();
Boss();
public: double salary; voidgiveRaise(double
void giveRaise(doubleamount);
amount);
Employee(); private:
public: Employee(string n, double s); Employee e;
string getName();
Employee(); };
double getSalary(); Boss::Boss() {}
Employee(string n, double s);
};
string getName(); void Boss::giveRaise(double amount)
Employee::Employee() : name(""), salary(0) {}
double getSalary();
Employee::Employee(string n, double s): name(n), salary(s) {} {
}; Employee::getName() { return name; }
string raiseSalary(amount,e);
e.salary = e.salary + amount;
Employee::Employee()
double Employee::getSalary(): name(""), salary(0)
{ return salary; } {} cout << e.getSalary() << endl;
e.salary << endl;
Employee::Employee(string
void raiseSalary(double a, Employee n, double
&e) s): name(n), salary(s) {} }
{string Employee::getName() { return name; }
e.salary
double+= a;// Normally not allowed
Employee::getSalary() to access
{ return e.salary
salary; }
} 7/2/2024 Object Oriented Concepts using C++ 86

You might also like