OBJECT ORIENTED PROGRAMMING IN C++
OBJECT ORIENTED PROGRAMMING IN C++ SATISH ANNIGERI
M.E. (Str.), Ph.D.
Professor of Civil Engineering B.V. Bhoomaraddi College of Engineering & Technology HUBLI 580 031
[email protected]
CONTENTS 1. Designing Software 2. Object Orientation 3. Object Oriented Programming in C++ 4. Summary of OOP 5. References
Computer Applications to Civil Engineering Problems Slide 1 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
DESIGNING SOFTWARE Goals In this section you will learn: v Why software systems need to be designed. v What the steps in software life cycle are. v What the different software design paradigms are.
Steps in Software Life Cycle v Requirements study: The need for the software are studied, and if it is determined that software is required, then its features and functionality are defined. v Systems analysis and Design: Once the features and requirements to be met by the software are defined, a detailed analysis of the processes and steps is carried out and blueprint for the structure and organization of the software is laid out. v Software Implementation: With the structure and organization of the software defined, a suitable programming language is identified that is well suited to implement the software. This process involves developing the software code, testing the code at each intermediate stage and debugging the code at each stage to eliminate logical errors. v Software Maintenance: Once the software is released for use, a software may need modification for two main reasons:
Computer Applications to Civil Engineering Problems Slide 2 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
BENEFITS OF MODELING A model is a simplification of reality. We build models so that we can better understand the system we are building.
AIMS OF MODELING 1. Models help us to visualize a system as it is or as we want it to be. 2. Models permit us to specify the structure or behavior of the system. 3. Models give us a template that guides us in constructing a system. 4. Models document the decisions we have made.
PRINCIPLES OF MODELING 1. The choice of what models to create has a profound influence on how a problem is attacked and how a solution is shaped. 2. Every model may be expressed at different levels of precision. 3. The best models are connected to reality. 4. No single model is sufficient. Every non-trivial system is best approached through a small set of nearly independent models.
Computer Applications to Civil Engineering Problems Slide 3 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
OBJECT ORIENTATION Goals In this section you will learn: v What Object Oriented Programming (OOP) is. v Master the vocabulary, rules and idioms of OOP.
Role of Object Orientation v A software design tool: As a tool for Object Oriented Analysis and Design (OOAD). Can be used independent of a programming language. Example: Unified Modeling Language (UML). v A software implementation tool: As a tool for implementing object oriented designs in software, called as Object Oriented Programming (OOP). A number of programming languages: C++, Java, C#, Object Pascal, Smalltalk, Simula.
Possible Reasons for Current Popularity of OOP [Budd, 1997] v The hope that it will quickly and easily lead to increased productivity and improved reliability. v The desire for an easy transition from existing languages. v The resonant similarity to techniques of thinking about problems in other domains.
Computer Applications to Civil Engineering Problems Slide 4 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
PROGRAM DESIGN PARADIGMS v Procedural programming paradigm: Emphasis is on accomplishing a task by sub-dividing a task into simpler tasks. Each task is implemented as an independent module, such as, a SUBROUTINE or FUNCTION in Fortran, PROCEDURE or FUNCTION in Pascal or functions in C, C++, and Java. o Each task is subdivided into further sub-tasks if it improves the organizational structure of the program. o Data is passed from one module to the other by various mechanisms, such as, parameters and arguments, COMMON variables, global variables. o Data is slave to functionality. v Object oriented programming paradigm: Emphasis is on identifying the data in the program and tasks are performed on the data. o Functions to be performed on the data are devised as a part of the data on which the functions act. o Actions are performed as a series of requests made by one data to another by passing messages. o Functions are slave to data.
Computer Applications to Civil Engineering Problems Slide 5 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
Fundamental Concepts of OOP v Objects – Composite bundles of attributes and behavior (Object = Attributes + Behaviour) v Class – Prototypes for creating objects. Specify the attributes (data) and behavior of objects v Data Hiding or Encapsulation – Minimize side effects of program modifications v Reuse – Containership, Inheritance and Templates v Class Hierarchies, Abstract Classes and Polymorphism
Computer Applications to Civil Engineering Problems Slide 6 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
OBJECT ORIENTED PROGRAMMING IN C++ Goal In this section you will learn: v How to implement OOP features in a C++ program.
Class, Data Hiding and Objects An example class to represent a quadratic equation: class quadEqn { private: double a, b, c, // coefficients x1, x2; // roots public: quadEqn() { a = b = c = 0.0; } // null constructor quadEqn(double aa, double bb, double cc) {a=aa; b=bb; c=cc; } // parameterized con quadEqn(const quadEqn &eqn) {a=eqn.a; b=eqn.b; c=eqn.c; } // copy constructor ~quadEqn() { } // destructor, empty because not essential double discriminant() { return (b*b) – (4*a*c); } // calculates discriminant int calcRoots(); void show() { cout << a << “\t” << b << “\t” << c << endl; } // prints the roots };
Computer Applications to Civil Engineering Problems Slide 7 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
Class, Data Hiding and Objects (contd.) 1.
2.
CONSTRUCTORS: Required to initialize objects at the time of instantiation (creation). a.
They have no return value.
b.
Their name is the same as the name of the class.
c.
They are automatically invoked whenever an object is being created. They cannot be explicitly invoked.
DESTRUCTORS: Required to perform clean up operations just before objects are destroyed. a.
A destructor is required only if the object performs dynamic resource allocation at run time
b.
A destructor has no return value
c.
A destructor has the same name as the name of the class preceded by the tilde (~) character.
d.
They are automatically invoked whenever an object is being destroyed. They cannot be explicitly invoked.
3.
MEMBER FUNCTIONS: Other member functions look similar to ordinary functions, except that they can only be invoked on behalf of an object and can never be invoked alone.
4.
INLINE MEMBER FUNCTIONS: Member functions defined within the class definition are inline functions. a. Wherever they are called, the entire body of the function is physically substituted b. This speeds up execution, but increases the size of the program.
5.
OTHER MEMBER FUNCTIONS: A member function can be defined outside the class definition.
6.
The class definition is terminated with the semicolon (;) after the closing curly brace (}).
Computer Applications to Civil Engineering Problems Slide 8 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++ 7.
Member data referenced in the member functions belongs to the object on behalf of whom the member function is invoked. a. The object invoking the member function will be known only when the program is written and not when the class is being defined. b. In the expression (b*b) – (4*a*c), a, b, and c belong to the object on behalf of whom the member function discriminant() will be invoked. The object that will invoke the member function will be only when this function is actually called in the main()or any other function. void main() { quadEqn eq1, eq2(2, 3, -1), eq3(eq2); eq1.show(); eq2.show(); eq3.show(); cout << eq2.discriminant() << endl; } The discriminant printed corresponds to the object eq2 because discriminant() is invoked by it.
Computer Applications to Civil Engineering Problems Slide 9 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
Defining Member Functions Outside the Class Definition An example: int quadEqn::calcRoots() { double d = discriminant(); if(d < 0) // complex roots. Don’t calculate. Simply return error code -1 { x1 = x2 = 0.0; return –1; } else if(d==0) { x1 = x2 = -b / (2*a); return 0; } else // d must be greater than 0 { x1 = (-d – sqrt(d) / (2*a); x2 = (-d + sqrt(d) / (2*a); return 1; } } Note The name of the member function must be fully qualified when written outside the class definition, otherwise it will be mistaken for a non-member function.
Computer Applications to Civil Engineering Problems Slide 10 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
OPERATOR OVERLOADING v The aim of the C++ class concept is to provide he programmer with a tool for creating new types that can be used as conveniently as the built-in types [Stroustrup, 2000]. v Built-in data types have the following features: o Assignment, Mathematical and logical operators are defined for them. o Input and output streams can be used for data input and output. v Similar features can be extended to User Defined Types through OPERATOR OVERLOADING. v This is made possible by: o considering operations as function calls, and o permitting co-existence of multiple functions with the same name but different parameters and/or return values. v The operation a + b is performed by the function call a.operator+(b) or alternately the function call operator+(a, b). In the first, operator+() is a member function invoked on behalf of the first operand a with second operand b supplied as the argument to the function. In the second, operator+() is a non-member friend function and both operands a and b are supplied as arguments to the function. v Programmer can define these operator functions relevant to the class being defined.
Computer Applications to Civil Engineering Problems Slide 11 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
ANOTHER EXAMPLE class Complex { private: double re, im; // real and imaginary parts of a complex number public: Complex() { re = im = 0; } // null constructor // parameterized constructor. Can convert a real number into a complex number Complex(double r, double i=0) { re = r; im = i; } Complex(const Complex &x) { re=x.re; im=x.im; } // copy constructor ~Complex() { }; friend Complex operator +(const Complex& a, const Complex &b); friend ostream& operator<<(ostream &s, const Complex &x); friend istream& operator>>(istream &s, Complex &x); };
Computer Applications to Civil Engineering Problems Slide 12 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
SOME OBSERVATIONS ON THE Complex CLASS 1. DEFAULT VALUES FOR CONSTRUCTOR PARAMETERS: If a parameter has a default value, the corresponding argument may be skipped when using the constructor. a. If a parameter has a default value, then all the succeeding parameters must also have default arguments. b. In the above example, the constructor is equivalent to two constructors, one with two parameters and another with only one parameter representing the real part while the imaginary part is made zero. 2. The same constructor is also capable of “converting” a real number into a complex number. This constructor is used to convert a “double” object to a Complex. 3. The compiler can generate generic constructors and destructors in case any required constructors or destructors are not furnished. However they are not guaranteed to work in case the classes carry out dynamic memory allocation and/or deallocation. 4. Friend functions are not member functions even though they are declared within the class definition. a. Friend functions are ordinary functions. b. They have special privilege to access the private member data and functions. c. Being non-member functions, they need not be attached to objects when they are being. 5. The friend privilege is against the concept of data hiding, but this concession is made in the interest of enhancing the usefulness of the class. 6. When friend functions are defined outside the class definition, their name must not be preceded by the class name as they are not member functions. The keyword friend is used only inside the class definition.
Computer Applications to Civil Engineering Problems Slide 13 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
FRIEND OR MEMBER FUNCTION? To decide whether an operator should be implemented as a member function or as a friend function, the following criterion may be employed: v If the operation involves the modification of the object on whose behalf the function is called, the operator must be implemented as a member function. The operators that belong to this category are the assignment operator(=), the increment/decrement operators (++, --), increment/decrement and assign (+=, -=).
ostream& operator<<(ostream &s, const Complex &x) { s << “(“ << x.re << “, “ << x.im << “)”; return s; } istream& operator>>(istream &s, Complex &x) { s >> x.re >> x.im; return s; }
Computer Applications to Civil Engineering Problems Slide 14 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
SOME THINGS THAT MAY NOT BE OBVIOUS void main() { Complex a(2, 3); double x=5; int i = 9; b = a + b = i + cout << cout <<
x; // a; // a + 5 2 + 5
Possible Possible << endl; << endl;
even though operator(Complex, double) is not defined even though operator(int, Complex) is not defined // operator+(Complex, int) // operator+(int, int)
} v If a required operator function is not available, the program attempts to convert the objects to a form for which operators are available. The constructor Complex(double) is used for this purpose. v Proliferation of operator functions can be avoided by supplying suitable data conversion constructors.
Computer Applications to Civil Engineering Problems Slide 15 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
REUSE – CONTAINERSHIP AND INHERITANCE v Reuse of data and code is an important objective of OOP. v Code reuse is supported by procedural programming languages through functions. v Mechanisms for reuse: • Containership – The new class contains an object of an existing class. Supported by both procedural and OO languages. • Inheritance – The new class is a specialized form of an existing class, enhancing and selectively modifying an existing class. Supported only by OO languages. v Containership is a “Has a” relationship. Alternately “Contains a”. v Inheritance is a “Is a” relationship. Alternately “Is a kind of”, “Is a sort of”.
Computer Applications to Civil Engineering Problems Slide 16 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
AN EXAMPLE FOR INHERITANCE class employee { protected: char *lname, *fname; public: void print(); }; void employee::print() { cout << “Employee name: “ << fname << “ “ << lname << endl; } // manager is derived from employee. class manager : public employee { protected: int numSub; // Number of subordinates public: void print(); // modifies the behavior };
Computer Applications to Civil Engineering Problems Slide 17 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++ void manager::print() { cout << “Manager name: “ << fname << “ “ << lname << endl; cout << “Number of subordinates: “ << numSub << endl; } void main() { employee emp(“raj”, “”); manager mgr(“ajay”, “”, 5); emp.print(); mgr.print(); } 1. An additional member data int numSub is added to the class manager. 2. If void print() were not defined in class manager, it would have inherited it from class employee.
Base class
employee
Derived class
manager
Computer Applications to Civil Engineering Problems Slide 18 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
POLYMORPHISM v Inheritance provides new functionality but adds to the complexity. void main() { employee emp(“raj”, “”); employee *mgr = new manager(“ajay”, “”, 5); emp.print(); mgr->print(); } v When dynamic memory allocation is used and objects are addressed through pointers, class of the object is determined at run time rather than at compile time. v Assuming that an employee pointer always points to an employee object leads to the incorrect call of print() of employee instead of print() of manager. v Polymorphism mechanism can solve this problem. class employee { protected: char *lname, *fname; public: virtual void print(); // virtual functions implement polymorphism };
Computer Applications to Civil Engineering Problems Slide 19 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
CLASS HIERARCHIES AND ABSTRACT CLASSES v A class hierarchy is represented by a tree diagram, with the base class at the root of the tree. v Usually, the base class at the root is abstract enough to have no physical meaning and hence need never be instantiated. v Such a class is an abstract class. v A class is treated as an abstract class if one or more of its member functions are abstract. v A member function Is designated as abstract by: o Not defining the member function, and o Adding “=0” in front of its declaration. v A child class can override an abstract function in its parent class to make it a non-abstract function. v If a child class over rides all the abstract functions of its parent classes, it becomes a “concrete” class. v Abstract functions are usually virtual functions as they are primarily used to implement polymorphism. Shape
Point
Line
Circle
Computer Applications to Civil Engineering Problems Slide 20 of 23
Triangle
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
TEMPLATES v Another mechanism for reuse is the TEMPLATE. Templates are parameterized classes. v One class definition creates one new data type. v One template class definition creates a series of classes, each of which is a new class. template class vector
{ private: int size; T *p; // pointer to data Public: vector(int sz=0) { if (sz > 0) { size=sz; p=new T[size]; } else {size=0; p=NULL; } } ~vector() { if (p!=NULL) delete [] p; }
void main() { vector vi(10); vector<double> vd(20); vector<employee> office(10); ... }
}; v Above main function requires the generation of three vector classes, namely, vector of integers, doubles and employees.
Computer Applications to Civil Engineering Problems Slide 21 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
SUMMARY 1. Everything is an object. 2. Computation is performed by objects communicating with each other, requesting that other objects perform actions. Objects communicate by sending and receiving messages. A message is a request for action bundled with whatever arguments may be necessary to complete the task. 3. Each object has its own memory, which consists of other objects. 4. Every object is an instance of a class. A class simply represents a grouping of similar objects, such as integers or lists. 5. The class is the repository for behavior associated with an object. That is, all objects that are instances of the same class can perform the same actions. 6. Classes are organized into a singly rooted tree structure, called the inheritance hierarchy. Memory and behavior associated with instances of a class are automatically available to any class associated with a descendant in this tree structure.
Computer Applications to Civil Engineering Problems Slide 22 of 23
AICTE–ISTE Short Term Course, MCE, Hassan
OBJECT ORIENTED PROGRAMMING IN C++
REFERENCES C Programming Language • Kernighan, B.W. and Ritchie, D.M., The C Programming Language, 2ed., Prentice Hall of India Pvt. Ltd., New Delhi, 1988. • Johnsonbaugh, R. and Kalin, M., Applications Programming in C, Maxwell Macmillan International Editions, Macmillan Publishing Co., New York, 1990.
C++ Programming Language • Stroustrup, B., The C++ Programming Language, Special Edition, Addison-Wesley, Reading, Massachusetts, 2000. • Hubbard, J.R., Schuam’s Outline of Theory and Problems of Programming with C++, 2ed., McGraw-Hill Book Co., New York, 2000. • Schildt, H., C++: The Complete Reference, Tata McGraw-Hill Publishing Co. Ltd., New Delhi, 1998. • Lippman, S.B. and Lajoie, J., C++ Primer, 3ed., Addison-Wesley, Reading, Massachusetts, 2000.
Opbject Oriented Programming • Booch, G., Rumbaugh, J. and Jacobson, I., The Unified Modeling Language User Guide, Addison-Wesley, Reading, Massachusetts, 1999. • Budd, T., An Introduction to Object Oriented Programming, 2ed., Addison-Wesley, Reading, Massachusetts, 1997. Computer Applications to Civil Engineering Problems Slide 23 of 23
AICTE–ISTE Short Term Course, MCE, Hassan