Professional Documents
Culture Documents
3003
Unit I 9 Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members Objects pointers and objects constant objects nested classes local classes Unit II 9 Constructors default constructor Parameterized constructors Constructor with dynamic allocation copy constructor destructors operator overloading overloading through friend functions overloading the assignment operator type conversion explicit constructor Unit III 9 Function and class templates - Exception handling try-catch-throw paradigm exception specification terminate and Unexpected functions Uncaught exception. Unit IV 9 Inheritance public, private, and protected derivations multiple inheritance virtual base class abstract class composite objects Runtime polymorphism virtual functions pure virtual functions RTTI typeid dynamic casting RTTI and templates cross casting down casting . Unit V ` 9 Streams and formatted I/O I/O manipulators - file handling random access object serialization namespaces - std namespace ANSI String Objects standard template library. Total: 45 TEXT BOOKS: 1. B. Trivedi, Programming with ANSI C++, Oxford University Press, 2007. REFERENCES: 1. Ira Pohl, Object Oriented Programming using C++, Pearson Education, Second Edition Reprint 2004.. 2. S. B. Lippman, Josee Lajoie, Barbara E. Moo, C++ Primer, Fourth Edition, Pearson Education, 2005. 3. B. Stroustrup, The C++ Programming language, Third edition, Pearson Education, 2004.
Unit I
Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members Objects pointers and objects constant objects nested classes local classes
Objects
An object is an encapsulation of both functions and data
Objects are an Abstraction represent real world entities Classes are data types that define shared common properties or attributes Objects are instances of a class All objects have attributes (characteristics), this is sometimes referred to as state. Objects have State have a value at a particular time Objects have Operations associated set of operations called methods that describe how to carry out operations (behavior) Objects have Messages request an object to carry out one of its operations by sending it a message messages are the means by which we exchange data between objects
Classes
Class : Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group. That group is termed as a class. Class has many other features like creation and implementation of the object, Inheritance etc.
classes
Every object belongs to (is an instance of) a class An object may have fields, or variables
The class describes those fields
The operations defined by the ADT are the only operations permitted on its data Example: a CheckingAccount, with operations deposit, withdraw, getBalance, etc.
Object-Oriented Concept
The rectangle area problem Define a class: Rect
Data: width, length Functions: compute_area()
Encapsulation
class Circle { private: int radius public: Circle(int r); // The area of a circle int compute_area(); }; }; class Triangle { private: int edgea, edgeb, edgec; public: Triangle (int a, int b, int c); // The area of a triangle int compute_area();
Example Code
class Rect { private: int width, length; public: Rect (int w, int l) { width = w; length = l; } int compute_area() { return width*length; } }
Method Tells the object how to respond to a message Our TV-01 objects respond to the following messages: Turn the television set on or off Change the channel Change the volume
Characteristics of OOPL
Encapsulation: Combining data structure with actions
Data structure: represents the properties, the states, or characteristics of objects Actions: permissible behaviors that are controlled through the member functions
C++ Construct(s)
Classes Classes Public and Private Members Operator overloading, templates, virtual functions Derived Classes
OOP Features
4 major features in OOP
encapsulation information hiding inheritance overloading
Encapsulation
an object encapsulates both its attributes & methods implications:
an attribute/ method is attached to an object/ class when you mention an attribute/ methods, you have to specify which object/ class it comes from
why encapsulation?
when you get hold of an object, you also get hold of its data & behaviour components good for reuse
Information Hiding
an object can hide its internal details
e.g. you dont know how your mobiles electronics works except punching the buttons
Inheritance
a class may be similar to another class but being more specialised
e.g. the class student is similar to the class person but student is more specialised
a person has attributes like: sex, age, name a student has all these + a student no.
Inheritance (contd)
a subclass
extends/ specialises a superclass inherits attributes & methods from its superclass may have more attributes/ methods than its superclass may change the content/ procedure of an inherited method
i.e. same method name/ signature but different behaviour
why inheritance?
reuse existing class definition customise/ specialise if needed
Overloading
different functions/ procedures/ methods can have the same name
provided that the parameters are of different types
giving a unique signature
the system will figure out which one to invoke e.g. you can have 2 procedures, both named call, taking a dog or person object as parameter respectively. Depending on you give it a dog or person object as the parameter, Java will know which one to use.
Why Overloading?
you can call the same method (name) but invoke different behaviour
dynamic binding of method
which method to invoke is determined at runtime
code reuse
in term of the calling code
Encapsulation is the mechanism that binds together code and data, and keeps both safe from outside interference or misuse. 1. Both data and member functions treated as single unit 2. Abstract focuses on behavior of object, encapsulation focuses on actual implementation 3. Encapsulation achieved through data hiding 4. For abstractions to work, implementations must be encapsulated.
Abstract Types
class Shape { public: Shape();
Advantages of Data Abstraction and Data Encapsulation Simplification of software development Testing and Debugging Reusability Modifications to the representation of a data type
Abstract Classes
May Contain abstract methods Some methods and data may be defined abstract class ColouredShape { private Colour c; // storage allocated for each public abstract void draw(); public Colour getColour() { return c; } public abstract void erase(); } No instances allowed Subclasses must implement all abstract methods or they are also abstract
Mortgage
Loan
29 of 10 slides
OO Concepts Overview
A Class
Encapsulation Hides the implementation details of a class Forces the user to use an interface to access data Makes the code more maintainable API doc as an example
INTRODUCTION TO C++
Inherit all ANSI C directives Inherit all C functions
comments
/* You can still use the old comment style, */ /* but you must be very careful about mixing them */ // It's best to use this style for 1 line or partial lines /* And use this style when your comment consists of multiple lines */
CLASSES
Access specifiers
Specify whether the data defined will be available to the users of the objects of the class. Public Private Protected Public: the data defined under public is available to objects. Private: data defined under private is not available to objects.
Class student { Public : int RollNo; private: string name; string address; public: void PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= X; // does not work since name is private student1.address= Y; // does not work since name is private Student1.PrintDetails(); }
Class student //defining function members outside class { Public : int RollNo; string name; string address; void PrintDetails(); //prototype };
void student :: PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= X; student1.address= Y; Student1.PrintDetails();
}
class student { public: static int PassingMark; int SubjectMark[5]; bool fail; void DisplayMarks() { for (int i=0;i<5;++i) , cout <<Marks of subject No.; cout <<i<<is <<SubjectMark*i+; } } void SetMarks (int Marks[5] { for (int i=0; i<5; ++i) { SubjectMarks[i]=Marks[i]; } } bool CheckPassing() { fail=false; for (int i=0;i<5; ++i) { if (SubjectMark[i]<PassingMark) fail= true; } if (fail) cout << congratulations! You are passing\n; else cout <<sorry ! You are failing\n; return !fail; }};
int student:: PassingMark; //required definition void main() { student::PassingMark=35; student X; student Y; int Xmarks[]={75,55,65,56,89}; int Ymarks[]={15,25,100,98,89}; X.SetMarks(Xmarks); Y.SetMarks(Ymarks); X.CheckPassing(); Y.CheckPassing(); }
Default Arguments
A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call. Syntax: return_type f(, type x = default_value,);
Function overloading
Function redefined with different set of arguments. EX: add(float, float) Add(int, int) Add (int, int, int) Function overloading is useful when similar function is required to be called with either variable number of arguments or arguments of different type or both.
Function Overloading
Two or more functions can have the same name but different parameters Example:
int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; }
What is a Friend Function? A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. How to define and use Friend Function in C++: The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument. Some important points The keyword friend is placed only in the function declaration of the friend function and not in the function definition. It is possible to declare a function as friend in any number of classes. When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend.
class class1 { private: int num; public: void get() { cout<<"Number:"; cin>>num; } friend void display(class1 cl); }; void display(class1 c1) { cout<<C1.NUM; } int main() { class1 cls; cls.get(); display(cls); }
Friend function
//static member friend function matrix multiplication #include<iostream.h> #include<conio.h> class matrixvector { static int a[3][3]; static int b[3]; static int c[3]; public: void getmatrix(void); void getvector(void); friend int multiply(matrixvector mv) };
void matrixvector::getvector(void) { cout<<"\n"; cout<<"\n enter the vector :"; for(int k=0; k<3;k++) { cin>>b[k]; } } int multiply(matrixvector mv) { cout<<"matrix - vector multiplication \n"; cout<<"\n the vector \n"; for(int m=0;m<3;m++) { cout<<"\n"; cout<<mv.b[m]; } cout<<"\n the matrix \n"; for(int i=0;i<3;i++) { for (int j=0; j<3; j++) { cout<<mv.a[i][j]; cout<<"\t"; }
cout<<"\n"; } for(int e=0;e<3;e++) { for(int d=0;d<3;d++) { mv.c[e]=mv.c[e]+mv.a[e][d]*mv.b[d]; }} cout<<"\n the result is \n"; for(int n=0;n<3;n++) { cout<<mv.c[n]; cout<<"\n"; } return 0; } int main() { clrscr(); matrixvector mv; mv.getvector(); mv.getmatrix(); multiply(mv); getch(); return 0;}
void PrintDetails()const { cout <<rollno; cout <<name; cout << address; rollno=4 //error } If rollno definition is changed to mutable int rollno; in the student class ,then there will not be an error.
Volatile functions
A member function invoked by a volatile object. A volatile object s value can be changed by external parameters which are not under the control of the program.
volatile member functions. Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object: class B { int x; public: void f() volatile; // volatile member function }; int main() { volatile B b; // b is a volatile object b.f(); // call a volatile member function safely } The object b is declared volatile. Calling a non-volatile member function from this object is unsafe, because b's state might have been changed by a different thread in the meantime. To ensure that f() can be called safely for a volatile object, it's declared volatile too.
10
What is a pointer?
int x = 10; int *p; p = &x; *p = 20;
20
What is a pointer?
int x = 10; int *p = NULL; p = &x; *p = 20; Declares a pointer to an integer & is address operator gets address of x
// ok // ok
A pointer can point to an object created by a class. Object pointers are useful in creating objects at run time. student s1; student *ptr = &s1; s1. getdata(); s1.show(); equivalent to ptr->getdata(); ptr-> show(); or (*ptr).show(); we can also create the objects using pointers and new operator student *ptr = new student; This allocates enough memory for the data members in the object structure and assigns the address of the memory space to ptr. We can also create an array of objects using pointers. student *ptr = new student[5];
constant objects
const student s1(x,y); // object s1 is constant Any attempt to modify the values of x and y will generate compile time error. A constant object can call only constant member functions. void PrintDetails()const { cout <<rollno; cout <<name; cout << address; }
nested classes
It is an another way of inheriting properties of one class into another. From this we can understand that an object can be collection of many other objects, that is a class can contain objects of other classes as its members . class alpha(); class beta(); class gamma { alpha a1; beta b1; }; All objects of gamma class will contain the objects a1 and b1. This kind of relationship is called containership or nesting.
local classes
Classes can be defined and used inside a function or a block. Such classes are called local classes. void test(int a) //function { .. class student //local class {.. .. //class definition -; student s1(a); //create student object . } Local classes can use global variables and static variables declared inside the function. Enclosing function cannot access the private member of a local class.