Sei sulla pagina 1di 58

VMKV ENGINEERING COLLEGE

DEPARTMENT OF CSE

OBJECT PROGRAMMING IN C++ II CSE / III SEM


PREPARED BY T.JAGADEESWARAN LECTURER/CSE

UNIT-I

FUNDAMENTAL CONCEPTS OF OOP: Objects Classes Encapsulation Inheritance Dynamic binding Message Passing Polymorphism

What is Object Oriented Programming?


Identifying objects and assigning responsibilities to these objects. An object is like a black box. Objects communicate to other objects by sending messages. The internal details are hidden. Messages are received by the methods of an object

What is an object?
Tangible Things Roles Incidents Interactions Specifications as a car, printer, ... as employee, boss, ... as flight, overflow, ... as contract, sale, ... as colour, shape,

Creating Classes
A class is a category of objects; it is a new data type
Classes provide a description of an object Classes provide a convenient way to group related data and the functions that use the data When you create an object from the class, you automatically create all the related fields You think about them and manipulate them as real-life classes and objects

Student aSophomore; aSophomore.idNum = 7645; cout<<aSophomore.idNum;

Error! By default, all members of a class are private

The two parts of an object


Object = Data + Methods

Inheritance
Inheritance means that one class inherits the characteristics of another class. This is also called a is a relationship:
A car is a vehicle

A dog is an animal

Data Hiding
Objects have associated data and functions
Objects restrict other parts of the program from accessing their member variables called data hiding Data hiding allows the creation of objects whose critical data is protected from corruption

Polymorphism
Polymorphism means having many forms. It allows different objects to respond to the same message in different ways, the response specific to the type of the object.

Encapsulation
A class is a unit of encapsulation Public operations, and private implementation.
The wrapping up of data and functions into a single unit called class is known as encapsulation

Two Programming Paradigms


Structural (Procedural) PROGRAM
FUNCTION

Object-Oriented PROGRAM
OBJECT
Operations

FUNCTION OBJECT FUNCTION


Operations Data

Data

OBJECT
Operations

Data

Benefits of object-oriented programming


Analyzing user requirements Designing software Constructing software
Reusability (reusable components) Reliability Robustness Extensibility Maintainability

Reducing large problems to smaller, more manageable problems

UNIT II

Introduction to Classes
A C++ class is used to create objects defined by the programmer, consisting of variables and functions
Define the class Rectangle: Tell the compiler what the class is made of class Rectangle Access specifiers { private: 3 member float width; Not accessible variables float length; outside the class float area; public: void setData ( float, float ); void calcArea ( ); Accessible 5 member functions float getWidth ( ); outside the class float getLength ( ); Prototypes used for manipulating member float getArea ( ); variables };

Defining Member Functions


Definitions of member functions are written outside the class declaration Scope resolution operator
void Rectangle :: setData ( float w, float l ) { Member function name Name of class width = w; Initializing private length = l; member variables } void Rectangle :: calcArea ( ) Member functions { Initializing private area = width * length; member variable can access member variables } within the class float Rectangle :: getWidth ( ) { Accessing the value return width; of a member variable } float Rectangle :: getLength ( ) { Accessing the value return length; of a member variable }
Return type

17

An Instance of a Class
After a class is defined, objects of the class can be declared
Class name Declare box an object of class Rectangle

Defines the class class Rectangle { private: float width; float length; float area; public: void setData ( float, float ); void calcArea ( ); float getWidth ( ); float getLength ( ); float getArea ( ); };

Rectangle box;
Initialize member variables width and length of box

box.setData ( 10.0, 12.5 );


Calling object
Member function

box.calcArea ( );
Calculates area member variable of box

cout << box.getWidth( );


Displays width member variable of box

Separate Specification and Implementation


Class declarations are stored in their own header file called the class specification file
Class specification file Name of header file rectangle.h for Rectangle class Use an identifier Extension similar to class name

Member functions definitions are stored in a separate .cpp file called the class implementation file
Name of implementation file Class implementation rectangle.cpp file for Rectangle class Extension

An application that uses the class should #include the specification file and link the implementation file with the main program
UNIX command line compile

g++ appProg.cpp rectangle.cpp


Application file Implementation file

Separate Specification and Implementation


class Rectangle { private: #include rectangle.h float width; void Rectangle :: setData ( float w, float l ). . . { public: width = w; void setData ( float, float ); length = l; . . . } float getArea ( ); . . . }; void Rectangle :: getArea ( ) { #include rectangle.h return area; void main ( ) } { Rectangle box; Implementation file: box.setData ( 10.0, 12.5 ); rectangle.cpp . . . Application program: cout << box.getArea ( ); appProg.cpp . . . Specification file: rectangle.h

Inline Member Functions


If the body of a member function is small, define it inline within the class definition
Inline functions are not called like regular functions The compiler replaces the inline function calls class Rectangle with the actually code of the function { This increases the size of the .exe but private: improves performance by cutting overhead float width; float length; Function body float area; void calcArea ( ) { area = width * length; } public: Inline instead of a separate void setData ( float, float ); function definition float getWidth ( ); float getLength ( ); float getArea ( ); };

Constructors
A constructor is a member function automatically called when a class object is created
Constructors have the same name as the class and are generally used for initialization purposes class Demo Program output: { In the constructor Prototype public: In main Demo ( ); Default constructor No return }; Demo :: Demo ( ) Definition of constructor type Class name Class name { cout << In the constructor\n; A default constructor } has no arguments void main ( ) { Constructor is executed here Demo demoObj; when object is declared cout << In main\n; }

Constructors
This constructor dynamically allocates memory for the desc array void main ( ) Constructor is executed { Memory allocated InvItem stock; stock.setInfo ( Hammer, 20 ); cout << stock.getDesc( ) << endl; cout << stock.getUnits ( ) << endl; }

class InvItem { private: char *desc; int units; Inline default constructor public: InvItem ( ) { desc = new char [51]; } void setInfo ( char *dscr, int un ) Program output: { strcpy ( desc, dscr ); Inline member units = un; } Hammer functions char *getDesc ( ) { return desc; } 20 int getUnits ( ) { return units; } };

Destructors
A destructor is a member function automatically called when an object is destroyed
Destructors have the same name as the class and are preceded by a tilde character ( ~ ) class Demo Constructor { void main ( ) executed public: { Constructor Demo ( ); Demo demoObj; Prototype for ~Demo ( ); Destructor cout << In main\n; Destructor Destructor } }; executed Demo :: Demo ( ) { cout << In the constructor\n; Program output: } In the constructor No Definition for Demo :: ~Demo ( ) In main return destructor { Class name type In the destructor cout << In the destructor\n; }

Destructors
The constructor dynamically allocates memory The destructor frees allocated memory void main ( ) Constructor is executed { Memory allocated InvItem stock; stock.setInfo ( Hammer, 20 ); cout << stock.getDesc( ) << endl; cout << stock.getUnits ( ) << endl; } Destructor is executed

class InvItem { private: char *desc; int units; public: Memory freed InvItem ( ) { desc = new char [51]; } ~InvItem ( ) { delete [ ] desc; } Inline default destructor void setInfo ( char *dscr, int un ) Program output: Inline member { strcpy ( desc, dscr ); Hammer functions units = un; } 20 char *getDesc ( ) { return desc; } int getUnits ( ) { return units; } };

Overloaded Constructors
More than one constructor can be defined for a class
A function name is overloaded when multiple functions with the same name exist void main ( ) Uses constructor with { character pointer argument InvItem item1 ( Hammer ); class InvItem InvItem item2; Uses default constructor { item1.setUnits ( 15 ); private: item2.setInfo ( Pliers, 25 ); char *desc; } int units; public: InvItem ( int size = 51 ) { desc = new char [ size ]; }
Same function name Constructor with a character pointer argument

Default constructor with one default argument

InvItem ( char *d ) { desc = new char [ strlen(d) + 1 ]; strcpy( desc, d ); } Different parameter lists void setInfo ( char *dscr, int un ) { strcpy ( desc, dscr ); units = un; } void setUnits ( int u ) { units = u; } . . . .

class Student { public: getName() { return name; } getGpa() { return gpa; } friend ostream & operator<<(ostream &, const Student &); private: char * name; float gpa; }; ostream & operator<<(ostream & out, const Student & s) { out << s.getName() << \t << s.getGpa(); return out; }

overloading output operator: as a friend function

Friend
Can access private member functions and private data attributes! Can be functions or classes Might not always be best solution

UNIT-III

Overloading
Use operator overloading to improve readability Avoid excessive or inconsistent usage Format Write function definition as normal Function name is keyword operator followed by the symbol for the operator being overloaded. operator+ would be used to overload the addition operator (+)

Assignment operator (=) may be used with every class without explicit overloading memberwise assignment Same is true for the address operator (&) Restrictions on Operator Overloading
Operators that can be overloaded
+ ~ /= <<= -new[] ! %= == ->* delete[] * = ^= != , / < &= <= -> % > |= >= [] ^ += << && () & -= >> || new | *= >>= ++ delete

Overloading Unary Operators


Overloading unary operators
Avoid friend functions and friend classes unless absolutely necessary. Use of friends violates the encapsulation of a class. As a member function: class String { public: bool operator!() const; ... };

Overloading Binary Operators


Overloaded binary operators
Non-static member function, one argument Non-member function, two arguments
class String { public: const String &operator+=( const String & ); ... };

y += z; equivalent to y.operator+=( z );

Example
class String { friend const String &operator+=( String &, const String & ); ... };

y += z; equivalent to operator+=( y, z );

Overloading ++ and - Pre/post-incrementing/decrementing operators


Can be overloaded How does the compiler distinguish between the two? Prefix versions overloaded same as any other prefix unary operator would be. i.e. d1.operator++(); for ++d1;

Postfix versions
When compiler sees postincrementing expression, such as d1++; Generates the member-function call d1.operator++( 0 ); Prototype: Date::operator++( int );

Templates
Templates
Easily create a large range of related functions or classes Function template - the blueprint of the related functions Template function - a specific function made from a function template

Class Templates
Class templates
Allow type-specific versions of generic classes

Format:
template <class T> class ClassName{
definition }

Need not use "T", any identifier will work To create an object of the class, type
ClassName< type > myObject; Example: Stack< double > doubleStack;

Template class functions


Declared normally, but preceded by template<class T> Generic data in class listed as type T Binary scope resolution operator used Template class function definition: template<class T> MyClass< T >::MyClass(int size) { myArray = new T[size]; }
Constructor definition - creates an array of type T

Function Templates
Function templates Compact way to make overloaded functions Keyword template Keyword class or typename before every formal type parameter (built in or user defined) template < class T > // or template< typename T > T square( T value1) { return value1 * value1; } T replaced by type parameter in function call int x; int y = square(x); If int parameter, all T's become ints Can use float, double, long...

UNIT IV

Inheritance
Inheritance Single Inheritance
Class inherits from one base class

Multiple Inheritance
Class inherits from multiple base classes

Three types of inheritance:


public: Derived objects are accessible by the base class objects (focus of this chapter) private: Derived objects are inaccessible by the base class protected: Derived classes and friends can access protected members of the base class

Base and Derived Classes


Often an object from a derived class (subclass) is an object of a base class (superclass)
Base class Student Shape Derived classes GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember CheckingAccount SavingsAccount

Loan

Employee Account

Implementation of public inheritance


class CommissionWorker : public Employee { ... }; Class CommissionWorker inherits from class Employee friend functions not inherited private members of base class not accessible from derived class

Overriding Base-Class Members in a Derived Class


To override a base-class member function In derived class, supply new version of that function
Same function name, different definition

The scope-resolution operator may be used to access the base class version from the derived class

Virtual Functions
virtual functions
Used instead of switch statements Declaration:
Keyword virtual before function prototype in base class

virtual void draw() const; A base-class pointer to a derived class object will call the correct draw function If a derived class does not define a virtual function it is inherited from the base class

Polymorphism
Polymorphism:
Ability for objects of different classes to respond differently to the same function call Base-class pointer (or reference) calls a virtual function C++ chooses the correct overridden function in object Suppose print not a virtual function
Employee e, *ePtr = &e; HourlyWorker h, *hPtr = &h; ePtr->print(); //call base-class print function hPtr->print(); //call derived-class print function ePtr=&h; //allowable implicit conversion ePtr->print(); // still calls base-class print

UNIT-V

Exception Handling
Errors can be dealt with at place error occurs
Easy to see if proper error checking implemented Harder to read application itself and see how code works

Exception handling
Makes clear, robust, fault-tolerant programs C++ removes error handling code from "main line" of program

Common failures
new not allocating memory Out of bounds array subscript Division by zero Invalid function parameters

Exception handling - catch errors before they occur


Deals with synchronous errors (i.E., Divide by zero) Does not deal with asynchronous errors - disk I/O completions, mouse clicks - use interrupt processing Used when system can recover from error Exception handler - recovery procedure Typically used when error dealt with in different place than where it occurred Useful when program cannot recover but must shut down cleanly

Exception handling should not be used for program control


Not optimized, can harm program performance

Exception handling improves fault-tolerance


Easier to write error-processing code Specify what type of exceptions are to be caught

Most programs support only single threads


Techniques in this chapter apply for multithreaded OS as well (windows NT, OS/2, some UNIX)

Exception handling another way to return control from a function or block of code

When Exception Handling Should Be Used


Error handling should be used for
Processing exceptional situations Processing exceptions for components that cannot handle them directly Processing exceptions for widely used components (libraries, classes, functions) that should not process their own exceptions Large projects that require uniform error processing

Basics of C++ Exception Handling: try, throw, catch


A function can throw an exception object if it detects an error Object typically a character string (error message) or class object If exception handler exists, exception caught and handled Otherwise, program terminates

Exception Specifications
Exception specification (throw list)
Lists exceptions that can be thrown by a function
Example:

int g( double h ) throw ( a, b, c ) { // function body } Function can throw listed exceptions or derived types If other type thrown, function unexpected called throw() (i.e., no throw list) states that function will not throw any exceptions In reality, function can still throw exceptions, but calls unexpected (more later) If no throw list specified, function can throw any exception

C++ Stream Input/Output


Stream A transfer of information in the form of a sequence of bytes I/O Operations: Input: A stream that flows from an input device ( i.e.: keyboard, disk drive, network connection) to main memory Output: A stream that flows from main memory to an output device ( i.e.: screen, printer, disk drive, network connection)

I/O operations are a bottleneck


The time for a stream to flow is many times larger than the time it takes the CPU to process the data in the stream

Low-level I/O
Unformatted Individual byte unit of interest High speed, high volume, but inconvenient for people

High-level I/O
Formatted Bytes grouped into meaningful units: integers, characters, etc. Good for all I/O except high-volume file processing

Iostream Library Header Files


iostream library: <iostream.h>: Contains cin, cout, cerr, and clog objects <iomanip.h>: Contains parameterized stream manipulators <fstream.h>: Contains information important to user-controlled file processing operations

Stream Input/Output Classes and Objects


ios: istream and ostream inherit from ios
iostream inherits from istream and ostream.

<< (left-shift operator)


Overloaded as stream insertion operator

>> (right-shift operator)


Overloaded as stream extraction operator Both operators used with cin, cout, cerr, clog, and with user-defined stream objects

Stream Manipulators
Stream manipulator capabilities
Setting field widths Setting precisions Setting and unsetting format flags Setting the fill character in fields Flushing streams Inserting a newline in the output stream and flushing the stream Inserting a null character in the output stream and skipping whitespace in the input stream

Potrebbero piacerti anche