Imagine a tollbooth at a bridge. Cars passing by the booth

91 Slides1.83 MB

Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that have gone by, and of the total amount of money collected.

In this railway reservation system, users can get both the train details and the train reservation details. The details to be provided for train are train no., train name, boarding point, destination point, no. of seats in first class and fare per ticket, no. of seats in second class and fare per ticket and date of travel.

When we take a mobile as an object, its basic functionality for which it was invented were Calling & Receiving a call & Messaging. But now a days thousands of new features & models were added & the count is still increasing. In above diagram, each brand (Samsung, Nokia, IPhone) have their own list of features along with basic functionality of dialing, receiving a call & messaging. When we talk about OOP, as the word indicate it will talk about an object (a real world object)

object Any real world entity which can have some characteristics or which can perform some work is called as Object. This object is also called as an instance i.e. - a copy of entity in programming language. If we consider the above example, a mobile manufacturing company, at a time manufactures lacs of pieces of each model which are actually an instance. This objects are differentiated from each other via some identity or its characteristics. This characteristics is given some unique name. Mobile mbl1 new Mobile (); Mobile mbl2 new Mobile ();

class 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. Considering the above example, A Mobile can be a class which has some attributes like Profile Type, IMEI Number, Processor, and some more.) & operations like Dial, Receive & SendMessage.

Classes A class is a way to bind the data & its associated functions together. It allows the data & function to be hidden ,if necessary ,from external use. Generally a class specification has two parts : 1.Class Declaration – it describes the type & scope of its members. 2.Class function definition – it describes how the class function are implemented.

Declaring a class The general form of a class declaration isClass class name { private: variable declaration; // data members or class members function declaration; public : variable declaration; // Member functions function declaration; };

Classes in C A class definition begins with the keyword class. The body of the class is contained within a set of braces, { } ; (notice the semi-colon). class class name { . . . }; Any valid identifier Class body (data member methods)

Classes in C Within the body, the keywords private: and public: specify the access level of the members of the class. the default is private. Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section.

Classes in C class class name { private: public: }; private members or methods Public members or methods

Classes in C Member public: access specifiers can be accessed outside the class directly. The public stuff is the interface. private: Accessible only to member functions of class Private members and methods are for internal use only.

Access specifiers

Access specifiers

Class Example This class example shows how we can encapsulate (gather) a circle information into one package (unit No need for others classes to or class) class Circle { private: double radius; public: void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; access and retrieve its value directly. The class methods are responsible for that only. They are accessible from outside the class, and they can access th member (radius)

Defining the Class test somedata 50 setdata)(d) showdata() 50

Creating an object of a Class Declaring a variable of a class type creates an object. You can have many variables of the same type (class). Instantiation Once an object of a certain class is instantiated, a new memory location is created for it to store its data members and code You can instantiate many objects from a class type. Ex) Circle c; test t;

Define Object from class classname objectname Example: test s1, s2; somedata s1 seddata)(d) showdata() test somedata s2 seddata)(d) showdata() Objects are sometimes called instance variables.

Complete Example

Call Member Function smallobj s1 smallobj smallobj s2 int somedata; void setdata(int d) { somedata d; } void showdata() { cout “Data is “ somedata; }; int somedata; void setdata(int d) { somedata d; } void showdata() { cout “Data is “ somedata; }; s1.setdata(1066) ; s2.setdata(1776) ; setdata(1066); setdata(1776); s1.showdata(); s2.showdata();

Creating and Using Rectangle Class // classes example #include iostream class CRectangle { int width, height; public: void set values (int,int); int area () { return (x*y); } }; void CRectangle::set values (int a, int b) { width a; height b; } int main () { CRectangle rect; rect.set values (3,4); cout "area: " rect.area(); return 0; } 25

Creating and Using Declares a class called CRectangle Rectangle Class Everything inside this // classes example #include iostream using namespace std; class CRectangle { int width, height; public: void set values (int,int); int area () { return (x*y); } }; Closing brace for the class opening brace and the corresponding closing brace (int a, int void CRectangle::set values b) is part of to the class { width a; height b; } int main () { CRectangle rect; rect.set values (3,4); cout "area: " rect.area(); return 0; } 28

Creating and Using Rectangle Class // classes example #include iostream using namespace std; void CRectangle::set values (int a, int b) { width a; height b; } class CRectangle { int width, height; public: int main () void set values (int,int); { int area () Function definition for set values is CRectangle rect; { class (3,4); rect.set values return done (x*y); outside the CRectangle definition itself. cout "area: " rect.area(); } return 0; We must use the operator of scope (::) }; to specify that we are }defining a function that is a member of the class CRectangle 29

Creating and Using Crea t of ty e an ob je pe C Rect ct (vari Rectangle Class m able angl gra ) ro p n mai r example O//uclasses #include iostream using namespace std; class CRectangle { int width, height; public: void set values (int,int); int area () { return (x*y); } };To access rect’s public members we use the object's name (rect) followed by a dot (.) and then the name of the member e. void CRectangle::set values (int a, int b) { width a; height b; } int main () { CRectangle rect; rect.set values (3,4); cout "area: " rect.area(); return 0; } 30

Constant Objects const objects using const keyword before object declaration. For example: const sample s ( m, n); // object s is constant

Static Object When an object is created as static, the lifetime of the object will exist throughout the program Execution and scope of the instance will also be maintained.

Static Object Example #include iostream.h #include iostream.h class classaccount account Account Account {{ int intacc no; acc no; constructor public: constructor public: account() Account account() Account {cout "Account constructor"; } {cout "Account constructor"; } constructor constructor account() account() Account {cout "Account Accountdestructor destructor {cout "Accountdesctructor"; desctructor"; }} }; }; void voidcreate stobj() create stobj() {{ account accountvip; vip; }} void sta voidmain(void) main(void) tic {{ acc ou clrscr(); clrscr(); nt vip account acc1; account acc1; ; Account create stobj(); Account create stobj(); constructor getch(); constructor getch(); }} Account Account constructor constructor

Static Data Members and Member Functions Static members are members that are single shared member common to all the objects created for a particular class. Memory allocation is done only once and not every time an object is created. Static functions can access only static variables Efficient when single copy of data is enough May seem like global variables, but have class scope Only accessible to objects of same class

Static Members contd., l Static Data Members: Object A Object B Object C Static variable

Static Members contd., Static Member Example class account { private: int currentBal; static int RateofInt; }; myclass A(0), B(1); Shared by all objects Ra te of In Object A currentBal 0 Object B t currentBal 1

Static Members contd., lStatic Data Members: class SavingsAccount { private: char name[30]; float total; float CurrentRate; public: SavingsAccount(); void EarnInterest() { total CurrentRate * total; } } Only one copy should be available as all objects should have same Interest rate To make CurrentRate accessible to all objects Declare CurrentRate as static float CurrentRate;

Constant data member and Constant Functions lA constant variable can be declared using const keyword lCompiler error results if attempted to modify it Syntax: const variable-name value Example: const int age 20; const int age; // Not valid

Constant data member and Constant Functions The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. int main() { const int i 5; -- Declaring a member function with the const } keyword specifies that the function is a "readonly" function that does not modify the object for which it is called. If a const function attempt to change the data, the compiler will generate an error message.

Constant data member and Constant Functions Illegal to declare a const member function that modifies a data member For built-in types it doesn’t matter whether we return by value as a const int fun1( ) {return 1;} int fun2( ) const {return 1;} main( ) { const int i fun1( ); int j fun2( ); --}

Constant data member and Constant Functions class Time { int hour; public: Time(int k) { hour k; } void update( ) { hour ; } int value( ) const { return hour; } void cheat( ) const { hour ;} }; void main (void) { Time t(10); cout t.value( ); } // error this is const 11

Constant data member and Constant Functions

Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that have gone by, and of the total amount of money collected. model this tollbooth with a class called tollbooth. The two data items are a type unsigned int to hold the number of cars and a type double to hold the total amount of money collected. A constructor initializes both of these to zero. A member function called payingcar() increments the car total and adds 0.50 to the total cash. Another function called nopaycar(), increments the car total but adds nothing to the cash total. Finally a member function called display() displays the two totals.

Constructors Classes control object initialization by defining one or more special member functions known as constructors. The job of a constructor is to initialize the data members of a class object. A constructor is run whenever an object of a class type is created. Constructors have the same name as the class. Unlike other functions, constructors have no return type. Constructors can not be virtual.

Constructors (Contd.) A class can have multiple constructors. Like any other overloaded function, the constructors must differ from each other in the number or types of their parameters. Constructors are the special type of member functions that initializes the object automatically when it is created. Compiler identifies that the given member function is a constructor by its name.

Types of constructors There are several forms in which a constructor can take its shape namely: Default Constructor Parameterized Constructor Copy Constructor

Default constructor Classes control default initialization by defining a special constructor, known as the default constructor. The default constructor is one that takes no arguments. If the class does not explicitly define any constructors, the compiler will implicitly define the default constructor. The compiler-generated constructor is known as the synthesized default constructor.

Default constructor -Example

Parameterized constructor A parameterized constructor is the one that has parameters or arguments specified in it. We can pass the arguments to constructor function when object is created. A constructor that can take arguments is called parameterized constructor. When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared.

Parameterized constructor Example

Copy constructor A copy constructor is a member function which initializes an object using another object of the same class. It is used to declare and initialize an object from another object. The most common form of copy constructor is shown here: classname (const classname &obj) { // body of constructor } Here, obj is a reference to an object that is being used to initialize another object. Copy constructor object creation: integer (integer & i) ; (or) integer I 2 ( I 1 ) ; (or) integer I 2 I 1 ;

Copy constructor – (contd ) The copy constructor creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to: Initialize one object from another of the same type. Copy an object to pass it as an argument to a function. Copy an object to return it from a function. The process of initializing through a copy constructor is known as copy initialization. A reference variable has been used as an argument to the copy constructor as we cannot pass the argument by value to a copy constructor.

Destructors A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope. A destructor will have exact same name as the class prefixed with a tilde ( ). It can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. The destructor is commonly used to "clean up" when an object is no longer necessary.

Destructors (contd.) Destructors are called when one of the following events occurs: An object allocated using the new operator is explicitly deallocated using the delete operator. A local (automatic) object with block scope goes out of scope. The lifetime of a temporary object ends. A program ends and global or static objects exist.

Destructor Example

Shallow copy A shallow copy means that C copies each member of the class individually using the assignment operator. The default copy constructor and default assignment operators it provides use a copying method known as a shallow copy (also known as a member wise copy). when designing classes that handle dynamically allocated memory, member-wise (shallow) copying ends up in a trouble. This is because the standard pointer assignment operator just copies the address of the pointer -- it does not allocate any memory or copy the contents being pointed to!

Deep copying The answer to the problem in the previous slide is to do a deep copy on any non-null pointers being copied. A deep copy duplicates the object or variable being pointed to so that the destination (the object being assigned to) receives it’s own local copy. This way, the destination can do whatever it wants to it’s local copy and the object that was copied from will not be affected. Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.

Shallow copy: Copies the member values from one object into another. Deep Copy: Copies the member values from one object into another. Any pointer objects are duplicated and Deep Copied. class String{ int size; char* data; }; String s1("Ace"); // s1.size 3 s1.data 0x0000F000 //In shallow copy the same location is pointed by both s1 and s2 objects String s2 s1; // s2.size 3 s2.data 0X0000F000 // In deep copy the data is copied to another location and both the objects point to the same data available in different locations. String s3 s1; // s3.size 3 s3.data 0x0000F00F // With “Ace” copied to this location.

Railway reservation problem

Output

In Lab Practice problems

Problem 1 Write a class definition that creates a class called leverage with on private data member, crowbar, of type int and one public function whose declaration is void pry(). Write a constructor that initializes to 0 the crowbar data. Assume that the constructor is define – Inside the class – Outside the class

Problem 2 Create a class called time that has separate int member data for hours, minutes and seconds. One constructor should initialize this data to 0. and another should initialize it to fixed values. Another member function should display it, in 11:59:59 format. The final member function should add two objects of type time passed as arguments. A main program should create two initialized time objects and one that isn’t initialized. Then it should add the two initialized values together, leaving the result in the third time variable.

Dynamic memory allocation Dynamic allocation is useful when – arrays need to be created whose extent is not known until run time – complex structures of unknown size and/or shape need to be constructed as the program runs – objects need to be created and the constructor arguments are not known until run time

Dynamic memory allocation Pointers need to be used for dynamic allocation of memory Use the operator new to dynamically allocate space Use the operator delete to later free this space

The new operator If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. If sufficient memory is not available, the new operator returns NULL. The dynamically allocated object/array exists until the delete operator destroys it.

The delete operator The delete operator deallocates the object or array currently pointed to by the pointer which was previously allocated at run-time by the new operator. – the freed memory space is returned to Heap – the pointer is then considered unassigned If the value of the pointer is NULL there is no effect.

Example int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 delete ptr; ptr NULL; 0EC4 0EC5 0EC6 0EC7

Example (Cont .) int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 delete ptr; ptr NULL; 0EC4 0EC5 0EC6 0EC7 0EC4

Example (Cont .) int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 0EC4 delete ptr; ptr NULL; 0EC4 0EC5 0EC6 0EC7 22

Example (Cont .) int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 0EC4 delete ptr; ptr NULL; Output: 22 0EC4 0EC5 0EC6 0EC7 22

Example (Cont .) int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 delete ptr; ptr NULL; 0EC4 0EC5 0EC6 0EC7 ?

Example (Cont .) int *ptr; ptr FDE0 ptr new int; FDE1 *ptr 22; FDE2 cout *ptr endl; FDE3 delete ptr; ptr NULL; 0EC4 0EC5 0EC6 0EC7 0

Dynamic allocation and deallocation of arrays Use the [IntExp] on the new statement to create an array of objects instead of a single instance. On the delete statement use [] to indicate that an array of objects is to be deallocated.

Example of dynamic array allocation int* grades NULL; int numberOfGrades; cout "Enter the number of grades: "; cin numberOfGrades; grades new int[numberOfGrades]; for (int i 0; i numberOfGrades; i ) cin grades[i]; for (int j 0; j numberOfGrades; j ) cout grades[j] " "; delete [] grades; grades NULL;

Dynamic allocation of 2D arrays A two dimensional array is really an array of arrays (rows). To dynamically declare a two dimensional array of int type, you need to declare a pointer to a pointer as: int **matrix;

Dynamic allocation of 2D arrays (Cont .) To allocate space for the 2D array with r rows and c columns: You first allocate the array of pointers which will point to the arrays (rows) matrix new int*[r]; This creates space for r addresses; each being a pointer to an int. Then you need to allocate the space for the 1D arrays themselves, each with a size of c for(i 0; i r; i ) matrix[i] new int[c];

Dynamic allocation of 2D arrays (Cont .) The elements of the array matrix now can be accessed by the matrix[i][j] notation Keep in mind, the entire array is not in contiguous space (unlike a static 2D array) The elements of each row are in contiguous space, but the rows themselves are not. – matrix[i][j 1] is after matrix[i][j] in memory, but matrix[i][0] may be before or after matrix[i 1][0] in memory

Example // create a 2D array dynamically int rows, columns, i, j; int **matrix; cin rows columns; matrix new int*[rows]; for(i 0; i rows; i ) matrix[i] new int[columns]; // deallocate the array for(i 0; i rows; i ) delete [] matrix[i]; delete [] matrix;

Pointers to objects

Pointers to objects Any type that can be used to declare a variable/object can also have a pointer type. Consider the following class: class Rational { private: int numerator; int denominator; public: Rational(int n, int d); void Display(); }; 82

Pointers to objects (Cont.) Rational *rp NULL; Rational r(3,4); rp &r; rp FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD 0

Pointers to objects (Cont.) rp Rational *rp NULL; Rational r(3,4); rp &r; numerator 3 denominator 4 r FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD 0 3 4

Pointers to objects (Cont.) rp Rational *rp NULL; Rational r(3,4); rp &r; numerator 3 denominator 4 r FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD FFF4 3 4

Pointers to objects (Cont.) If rp is a pointer to an object, then two notations can be used to reference the instance/object rp points to. Using the de-referencing operator * (*rp).Display(); Using the member access operator - rp - Display();

Dynamic Allocation of a Class Object Consider the Rational class defined before Rational *rp; int a, b; cin a b; rp new Rational(a,b); (*rp).Display(); // rp- Display(); delete rp; rp NULL;

malloc() vs new new calls constructors malloc() directly calls memory location through function Primitive data types (char, int, float. etc) can also be initialized with new. For example, below program prints 10. new returns exact data type malloc() returns void *.

delete and free() in C delete operator used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer. free() used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

Back to top button