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

Module2 Mix

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

Module2 Mix

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

Amity School of Engineering & Technology

Object Oriented Programming


using
Contents Amity School of Engineering & Technology

 Object & classes, attributes, methods


 C++ class declaration
 Local Class and Global Class
 State identity and behaviour of an object
 Local Object and Global Object
 Scope Resolution Operator
 Abstract data types
 Friend Function
 Inline Functions
 Constructors and Destructors
 Types of Constructors
 Static Class Data
 Array of Objects
 Constant Member functions and Objects
 Memory Management System
State identity and behaviour of an object
Amity School of Engineering & Technology

 Methods take an Object from one State to Another


 A method may be called only when an Object is in a selected set of states.
– Example: FileHandler:
• Open may be called only if state is not open
• Close may be called only if the state is open
 Conditions: Pre-Conditions & Post-Conditions
– Pre-Condition (Advertised Requirements)
• Must be satisfied for proper/guaranteed execution of function.
– Post-Condition (Advertised Promises)
• Guaranteed State of the Object upon completion of function
Local Object and Global Object Amity School of Engineering & Technology

 Global objects can be used by anyone.


 Local objects are limited in scope to their specific function, or control statement.

1) Generally, avoid global objects for the following reasons:


Anyone can modify them at any time. It's hard to be sure that a global object has
valid data.
2) Name conflicts get more likely and you might get into problems when using 3rd
party libraries, or when combining code from multiple sources.
 Namespaces help with the name conflicts, but keeping data limited to the code
where it is needed is very important
Abstract data types Amity School of Engineering & Technology

Abstract data type(ADT) is composed of:


 Collection of data
 Set of operations on that data
Specification and Implementation of ADT
 Includes choosing a particular data structure
A data structure is a construct that can be defined in a
programming language to store a collection of data
Attributes in C++ Amity School of Engineering & Technology

 An attribute acts as an annotation or a note to the compiler which


provides additional information about the code for:
 optimization purposes
 enforcing certain conditions on it.
 Allows the programmer to specify additional information to the
compiler to enforce constraints(conditions)
 Optimise certain pieces of code or do some specific code
generation.
Purpose of Attributes in C++ Amity School of Engineering & Technology

To enforce constraints on the code:

With Constraints With Attribute


int f(int i)[[expects:i > 0]]
int f(int i) {
{ // Code
if (i > 0) }
return i;
else
return -1;

// Code
}
Purpose of Attributes in C++Amity School of Engineering & Technology
To give additional information to the compiler for optimization
purposes
Special Case 1 Special Case 2
#include <iostream>
int f(int i)
#include <string>
{
int main()
switch (i) {
{
case 1:
// Set debug mode in compiler or 'R'
[[fallthrough]];
[[maybe_unused]] char mg_brk = 'D';
[[likely]] case 2 : return 1;
// Compiler does not emit any warnings
}
// or error on this unused variable
return -1;
}
}
Inline Functions Amity School of Engineering & Technology

 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 Functions Amity School of Engineering & Technology

#include <iostream>
Output
using namespace std;
Max (20,10): 20
inline int Max(int x, int y) {
return (x > y)? x : y; }
Max (0,200): 200

// Main function for the program Max (100,1010): 1010


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; }
Array of Objects Amity School of Engineering & Technology

• Like array of other user-defined data types, an array of type


class can also be created.
• The array of type class contains the objects of the class as its
individual elements.
• Thus, an array of a class type is also known as an array of
objects.
• An array of objects is declared in the same way as an array of
any built-in data type.
Syntax:
class_name array_name [size] ;
Array of Objects Amity School of Engineering & Technology

#include void main()


<iostream> {
class MyClass MyClass obs[4];
{ int i;
int x; for(i=0; i < 4; i++)
Output
public: obs[i].setX(i);
obs[0].getX(): 0
void setX(int i) { x for(i=0; i < 4; i++)
obs[1].getX(): 1
= i; } cout << "obs[" << i << "].getX(): " <<
obs[2].getX(): 2
int getX() { return obs[i].getX() << "\n";
obs[3].getX(): 3
x; } getch(); }
};
Constant Member functions and Objects
Amity School of Engineering & Technology

• Principle of least privilege


– Only give objects permissions they need, no more
• Keyword const
– Specify that an object is not modifiable
– Any attempt to modify the object is a syntax error
– Example
const Time noon( 12, 0, 0 );
• Declares a const object noon of class Time and
initializes it to 12
Constant Member functions and Objects
Amity School of Engineering & Technology

• const objects require const functions


– Member functions declared const cannot modify their object
– const must be specified in function prototype and definition
– Prototype:
ReturnType FunctionName(param1,param2…) const;
– Definition:
ReturnType FunctionName(param1,param2…) const { …}
– Example:
int A::getValue() const { return
privateDataMember };
• Returns the value of a data member but doesn’t modify anything so is declared const
• Constructors / Destructors cannot be const
– They need to initialize variables, therefore modifying them
Constant Member functions Amity School of Engineering & Technology

 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.
syntax
datatype function_name const();
Constant Member functions
Amity School of Engineering & Technology

Output
The value using object d : 28
The value using object d1 : 8
Memory Management System Amity School of Engineering & Technology

There are essentially two types of memory allocation


Static – Done by the compiler automatically (implicitly).
Global variables or objects -- memory is allocated at the start of the program, and freed
when program exits; alive throughout program execution
Can be access anywhere in the program.
Local variables (inside a routine) – memory is allocated when the routine starts and freed
when the routine returns.
A local variable cannot be accessed from another routine.
Allocation and free are done implicitly.
No need to explicitly manage memory is nice (easy to work with), but has limitations!
 Using static allocation, the array size must be fixed.
 Consider the grade roster for the class? What is the number of people in the class?
Memory Management System Amity School of Engineering & Technology

• There are essentially two types of memory allocation


Wouldn’t it be nice to be able to have an array whose size can be adjusted
depending on needs.
 Dynamic memory allocation deals with this situation.

Dynamic – Done explicitly by programmer.


Programmer explicitly requests the system to allocate memory and return starting
address of memory allocated (what is this?). This address can be used by the
programmer to access the allocated memory.
When done using memory, it must be explicitly freed.
Explicitly allocating memory in C++:
Amity School of Engineering & Technology

The ‘new’ Operator


• Used to dynamically allocate memory
• Can be used to allocate a single variable/object or an array of
variables/objects
• The new operator returns pointer to the type allocated
• Examples:
– char *my_char_ptr = new char;
– int *my_int_array =new int[20];
– Mixed *m1 = new Mixed(1,1,2);
Explicitly freeing memory in C++: Amity School of Engineering & Technology

the ‘delete’ Operator


 Used to free memory allocated with new operator
 The delete operator should be called on a pointer to dynamically allocated memory
when it is no longer needed
 Can delete a single variable/object or an array
 delete PointerName;
 delete [] ArrayName;
 After delete is called on a memory region, that region should no longer be accessed by
the program
 Convention is to set pointer to deleted memory to NULL
 Any new must have a corresponding delete --- if not, the program has memory leak.
 New and delete may not be in the same routine.
Why use dynamic memory allocation?
Amity School of Engineering & Technology

• Allows data (especially arrays) to take on variable sizes (e.g.


ask the user how many numbers to store, then generate an array
of integers exactly that size).
• Allows locally created variables to live past end of routine.
• Allows us to create many structures used in Data Structures and
Algorithms
Amity School of Engineering & Technology

The . and -> operators


• The dot operator is used to access an object’s members
– M1.Simplify();
– M1.num = 5;
• But how do we access an objects members if we only
have a pointer to the object?
• If we have M1_ptr = &M1, Perhaps we would use
(*(M1_ptr)).Simplify()
• A shorthand for this is the arrow operator
• M1_ptr->Simplifly() is equivelant to(*(M1_ptr)).Simplify()
sample8.cpp
Amity School of Engineering & Technology

The Heap
• Large area of memory controlled by the runtime system that is
used to grant dynamic memory requests.
• It is possible to allocate memory and “lose” the pointer to that
region without freeing it. This is called a memory leak.
• A memory leak can cause the heap to become full
• If an attempt is made to allocate memory from the heap and
there is not enough, an exception is generated (error)
Explicit memroy allocation/ Amity School of Engineering & Technology

free in C (Works also in C++)


• The malloc and free routines
– Prototype defined in stdlib.h
– malloc is similar to new except that it specifies the exact memory size
• Return a (void *) -- needs to convert to the right pointer type
– free is equivalent to delete (only one form for both single item and
many items).
Amity School of Engineering & Technology

Thanks

You might also like