Você está na página 1de 50

OOP & Data Structures using C++

Lecture 1

Course information
Text Books
1. Object oriented programming in C++ by Robert Lafore (3rd

Edition) 2. Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto Tamassia

Reference books
1. 2. 3.

4.
5. 6.

C++ How to Program by Deitel & Deitel (3rd Edition) Data Structures, Schaums outline series Data Structures and Program Design in C++ by Robert L. Kruse and Alexender J. Ryba Thinking in C++ by Bruce Eckel Data Structures using C and C++ by Aaron M. Tenenbaum The C++ programming language by Bjarne Stroustrup

Course Work & Grading Criteria


6 assignments & 6 quizzes
3 assignments & 3 quizzes before mid-term 2 un-announced/surprise quizzes and 1 announced quiz 3 assignments & 3 quizzes after mid-term 2 un-announced/surprise quizzes and 1 announced quiz

Reading assignment per week Evaluation of programming assignments on the

basis of viva conducted at the time of submission of the particular assignment

Programming paradigms
Procedural programming
Centered around procedures( also called functions) Data + procedures to operate on the data Data and procedures are unrelated to each other

Object-oriented programming
Centered around classes Data + functions to operate on the data but encapsulated to

form an entity ( called object)

Truths about software developments


Concerned parties and their concerns
1. Users Reliability Faster speed 2. Project managers & Developers Program efficiency Maintainability Extensibility Reliability Code reusability Easier to modify, extend

Stages of software development


1.

2.
3. 4. 5.

Analysis( information gathering) Design Implementation Testing Documentation Documentation is an important step in software development
For maintaining a software For extending a software

Problem with procedural languages


Can not handle the complexity of large programs

Provide poor model of real world


Functions and data are unrelated

Functions have unrestricted access to global data

Programs become difficult to modify/enhance


Modification in one part can have unwanted effects on the

other parts

Object-oriented languages
Think in terms of objects

Provide good model of real world entities


Data attributes/characteristics Function behavior

Reusability
Inheritance

Object-oriented programming
Aimed at programmers engaged in demanding real

world projects Increases productivity Fewer people Less time Reduced Complexity Internal discipline of program in the program organization External discipline of program in documentation Programs are Easier to understand Easier to maintain

Fundamentals of object-oriented programming


1) Abstraction
Create new abstract data types (called classes) that

match the real world entities New types can be used exactly as built-in data types Overload existing operators to operate on new data types

2) Encapsulation / Isolation
Data and behavior are coupled inside an entity

called object

10

3) Inheritance

the ability to compose new abstractions from

existing one a re-use of common interface and implementation Person Student Removes redundancy so easy to maintain program Name Name results
Attendence

11

4) Polymorphism One thing in many different forms Like a politician before and after an election, for example

5) Information hiding Provide the user with just interface Implementation details are hidden Protect the data from accidental manipulations

Introduction to C++
C++ developed by Bjarne Stroustrup at AT&T Bell

13

Laboratories Initially called C with classes C is a subset of C++ Every statement of C is correct in C++, vice-versa may not be true C++ is a general purpose programming language that is a better C Pre-processors are eliminated for value substitution Const is used instead of #define Function overloading Two or more functions may be given the same name provided the type signature for each function is unique C++ type string instead of character arrays New and delete instead of malloc(), realloc() etc

Introduction to C++ contd


Comments (// used instead of /* */) In C, declarations must be at the start of a block

In C++, declarations can be anywhere in a block but before the use of the variable in a statement The C++ code: {... for (int i = 0 ; i < size ; i++) {...}...
is equivalent to C code: { int i ; . . . for (i = 0 ; i < size ; i++) {...}
14

Introduction to C++ contd


Exception handling: handling run-time errors C++ standard library supports object-oriented programming Supports generic programming And many more..

Points to remember
Every statement of C is correct in C++, vice-versa may not

be true Apart from some new features added in C++, the basic difference in C and C++ is the organization of a program. Organizational principles of C and C++ are different

15

Concepts in Object-Oriented Design


CLASS

An IMPORTANT FACET of OOD and C++ A set of homogeneous objects An Abstract Data Type (ADT) -- describes a new data type A collection of data items or functions or both Represents an entity having
Characteristics Attributes (member data or data members) Behavior Functionality (member functions)

Provides a plan/template/blueprint
Is just a declaration Is a description of a number of similar objects

Class Definition is a Type Declaration -- No Space is

Allocated
16

Declaration Vs Definition
Declaration
Describes the form of an Object DOES NOT Reserve Any Storage Initialization is NOT Allowed

Definition
Creates an Instance( also called object) Reserves a Storage Initialization is Allowed

All Objects MUST BE DEFINED BEFORE THEIR

USE
17

Syntax of a Class
class Class_Name{ private: //Default and Optional member_specification_1; : member_specification_n; public: member_specification_n+1; : member_specification_n+m; }; //Don't forget the semicolon after the closing brace.

Each class declaration starts with the keyword class followed by the name of the class. The definition of the class falls between the open and closed braces that follow the class name.
18

Structure of a Class
Data Members Member Functions Accessing Rights -- public, private, and protected Data members are variables of either

fundamental data types or user defined data types. Member functions provide the interface to the data members The default member accessibility is private, means that only class members can access the data member or member function.
19

Accessing Rights

Private: member functions of the class and its friends Protected: member functions and derived classes Public: entire world Thumb rule -- data members are kept private and member functions are kept public
members.

A client uses the public interface, meaning it accesses public

Reason for limiting access

Restricting users to intentionally or

unintentionally modifying the parts that they are not supposed to change

20

Relationship between objects and classes


A class is an Abstract/user defined data type

An object is an instance of a class just as in

int x; x is an instance of integer type

21

Example of class: A Classroom


Attending the lecture we

have several individuals


A bunks the classes B is a regular student C- doesnt submit

assignments D - does nothing


These are the students
A B C D

of our class
Note that the individuals are not identical
22

Abstraction and Classes


From our perspective, we see them as an instantiation of

a "Class", Student

has a name attends class has a grade completes assignments


Note the each student looks the same even though the are different individuals
Student

Name Grade Attendance Record Complete Assignment() Attend Class()

A Class defines an "Abstraction"

23

Objects, Instances of a Class


Classes define what properties will exist in each

instance Objects are distinct instances that exhibit those properties



Student
Name Grade Attendance Record Complete Assignment() Attend Class()

24

Objects, Instances of a Class


Classes define what properties will exist in each instance Objects are distinct instances that exhibit those properties

Class

Student
Name Grade Attendance Record Complete Assignment() Attend Class()

Objects

B : Student Name=B Attendance=100% Grade=A

Notice that the data members are replicated in each object. Each object is an instance of Student. It does not make sense to replicate member functions.

D : Student Name=D Attendance=85% Grade=B

A programming example of class


#include <iostream.h> class prize { private: int amount; public: void set_val(int val) { amount=val; } void get_val() { cout<<"amount you have won is: "<<amount<<endl; } };

26

An example of a class contd


void main() { prize p; p.set_val(10000); p.get_val(); } Objects of a class are also called instances Creating an instance of a class/ object creation is also

called instantiating //the dot operator is called member access operator Every call to member function is associated with some object Member function has access to all other members of the class public or private
27

Inline functions
Instead of making a jump to the code of function,

compiler places the code at the point the call is made Functions defined inside the class body are inline by default Inline keyword is used to request compiler to make a function inline
Used with declaration Used with definition

28

Constructor
Special member function -- same name as the class

name Used for


initialization of data members acquisition of resources

Does not return a value Implicitly invoked when objects are created Can have arguments Cannot be explicitly called Multiple constructors are allowed If no constructor is defined in a program, default constructor is called
no arguments

29

#include <iostream.h> class complex { private: double re, im; public: complex():re(0), im(0) //initializer list {} void set_val(double r, double i) { re=r; im=i; } void show() { cout<<"complex number: "<<re<<"+"<<im<<"i"<<endl;
} };

Constructor Example

30

void main()

{
} Output:

complex c1; c1.show();

31

Complex number: 0+0i Initializer list: the order of member initialization is not governed by the order in initializer list but on the basis of the order in which members are declared in the class

Constructor Overloading
Can have more than one constructors in a class
Different signatures

Which constructor is called depends on the

number of arguments used in object definition

32

33

#include <iostream.h> class complex { private: double re, im; public: complex():re(0), im(0) {} complex(double r, double i):re(r), im(i) {} void set_val(double r, double i) { re=r; im=i; } void show() { cout<<"complex number: "<<re<<"+"<<im<<"i"<<endl; } };

Constructor Overloading Example

void main()
{ } The output would be
complex number: 3+4.3i complex number: 2+5.5i

complex c1(3, 4.3); complex c2; c1.show(); c2.set_val(2, 5.5); c2.show();

34

The default copy constructor


An object can be initialized with another object of

the same type No special constructor needs to be written Default copy constructor already built into all classes

35

Example: Default copy constructor


Same class definition of complex class as earlier void main() { complex c1(4, 2); complex c2(c1); //same as c2=c1 complex c3=c1; c1.show(); c2.show(); c3.show(); } Output: complex no: 4+2i complex no: 4+2i complex no: 4+2i

36

Destructor
Special member function used for clean-up --

same name as the class name with a tilde (~) One single destructor
Destructor overloading not allowed

Cannot accept parameters and does not return a

value Invoked when an object gets out of scope or when object gets destroyed Reverses the effects of constructor
must be reverted by using delete in destructor

All dynamic allocations done in the class using new

37

Destructor Example
#include <iostream.h>
class complex { private:


38

double re, im; public: complex():re(0), im(0) //initializer list {} ~complex() {//perform resource release } void set_val(double r, double i) { re=r; im=i; } void show() { cout<<"complex number: "<<re<<"+"<<im<<"i"<<endl; } };

void main() { complex complex complex c1.show(); c2.show(); c3.show(); }

c1(4, 2); c2(c1); //same as c2=c1 c3=c1;

Defining member functions outside the class


Member functions defined inside a class are inline by

default Declaration and definition can be separated from each other


Declaration inside the class Definition outside the class

Syntax: Return_type class_name :: ftn_name (list of parameters) { Body of function }


//:: operator is called scope resolution operator //specifies to which class something is associated with
40

41

#include <iostream.h> class complex { private: double re, im; public: complex(); complex(double r, double i); void show(); }; complex::complex(): re(0), im(0) {} complex::complex(double r, double i): re(r), im(i) {}

void complex::show()
{ }

cout<<"Complex no: "<<re<<"+"<<im<<"i"<<endl;

42

Objects as function arguments


A member function has direct access to the data

members of the class public or private But indirect access to other objects of the same class that are passed as arguments
Indirect access: using object name, a dot, and the

member name

43


44

#include <iostream.h> class complex { private: double re, im; public: complex():re(0), im(0) {} complex(double r, double i):re(r), im(i) {} void add(complex a, complex b) { re=a.re + b.re; im=a.im + b.im; } void show() { cout<<"Complex no: "<<re<<"+"<<im<<"i"<<endl; } };

Example: Add two complex numbers

void main() { complex complex }


45

c1(4, 2); c2(2.1, 3); c3;

complex c3.add(c1, c2); c1.show(); c2.show(); c3.show();

Objects in Memory
Each object has its own separate data items Each object is allocated space equal to the aggregate

of the space of all data items at the time of object definition All objects of a given class use the same member functions Member functions are placed in memory once --when they are defined in class declarations
Function space is common for each object of a class

All objects of the class share the same function

instance
no conflict arises since only one function is executed at

a time

46

Object1 Data 1 Data 2

Object2 Data 1 Data 2

Object3 Data 1 Data 2

Function()1 Function()2

47

The This pointer


Functions are defined only once but data

members are defined separately for each object When a function is called on an object, how does the function know which object to act upon? The answer is the this pointer.
A Pointer to the Object, which is Used in Member

Function Invocation this


Address of each object (stored in the this

pointer) is passed to the calling function


If a function has n parameters, there are n+1

parameters sent
Since there is only one copy of functions, the
48

this pointer is the only way through which a function knows which object data to operate on

Complex() { re=0; im=0; } //the above code is treated by the compiler as Complex () { this->re=0; this->im=0; }
49

Summary
Object-oriented programming makes code easier

to write, understand, maintain, and document Entities in real-world are in direct correspondence with their programming model Abstraction, Encapsulation, Inheritance, Polymorphism, and Data Hiding are the key aspects of OOP

50

Você também pode gostar