1 / 204

Object Oriented Programming with C++

Object Oriented Programming with C++. Class : MCA - II Semester. Contents. Overview of C++ Sample C++ program Data types Operators Expressions Statements Arrays Strings. Pointers User defined types Function components Argument passing Inline functions Function overloading

joan-craft
Télécharger la présentation

Object Oriented Programming with C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Programming with C++ Class : MCA - II Semester

  2. Contents • Overview of C++ • Sample C++ program • Data types • Operators • Expressions • Statements • Arrays • Strings • Pointers • User defined types • Function components • Argument passing • Inline functions • Function overloading • Recursive functions

  3. Overview of C++ • Object oriented programming is a programming paradigm. • Tool which is used to build more reliable and reusable system. • Two types of programming paradigms • Procedure oriented programming • Object oriented programming

  4. Structured programming • Gives importance to the logic rather than data. • Emphasis on algorithm rather than data. • Programs are divided in to modules. • Independent functions (procedure) to discrete tasks. • Do not support inheritance and polymorphism. • In procedural languages like FORTRON, PASCAL, COBOL, C etc. a program is a list of instructions. • Each statement in the program tells the computer to do something. • Procedural approach has its own limitations. • Division into functions • Complex • Data undervalued

  5. Division into functions: • loosely defined discipline • Program divided into number of functions. • Grouping number of functions into larger entity called module. • Complex: • Large programs become complex to debug and maintain. • Data undervalued: • Importance to actions and not for the data • Data is not secure. • Any function can access the global variable and changes its values.

  6. Object oriented programming • To overcome the limitation of the procedural language the OOP concept was developed. • New way of solving problems with computers. • OOP languages provide the programmer, the ability to create class hierarchies. • Programmer can create modular and reusable code. • Can modify the existing modules. • The fundamental idea behind object oriented languages is to combine into a single unit, both data and functions. Such a unit is called as object.

  7. Functions inside the objects are called as member functions and these member function provide the way to access data. • If you want to read a data item in an object then you call the member function in the object. • It will read that data item in an object and returns the value. You cant access the data directly. Data is hidden. • Data and its functions are said to be encapsulated into single entity called object.

  8. OOPS definition: OOPS can be defined as technique by which a computer program is designed and written around the objects. • The fundamental features of OOPs are • Encapsulation • Data Abstraction • Inheritance • Polymorphism • Message passing • Extensibility • Persistence • Delegation • Genericity • Multiple inheritance

  9. Class • Class is a template (format). • The C++ class mechanism allows users to define their own data types. • For this reason, classes are called user-defined types. • A class definition has two parts: • class head - composed of the keyword class followed by the class name • class body - enclosed by a pair of curly braces. • A class definition must be followed either by a semicolon or a list of declarations. • For example: • class Screen {……………... }; • class Screen { .............. } myScreen, yourScreen;

  10. Objects • a class is a logical abstraction. • An object has physical existence. • An object is an instance of a class. • An object is a combination or collection of data and code designed to emulate a physical or abstract entity. EX: class Screen { .............. } myScreen, yourScreen; • Screen – class name • myScreenand yourScreenare objetcs. • The general form of class and its object lists looks as below: class class-name { private data and functions access-specifier: data and functions access-specifier: data and functions // ... access-specifier: data and functions } object-list;

  11. Example for representation of class Class account { private: char name[20]; // data members int acc_type; int acc_no; float balance; public: deposite(); // member functions withdrow(); enquire(); };

  12. Objects serve the following purposes: • Understanding the real world and a practical base for designers. • Decomposition of a problems into objects depends on judgment and nature of the problem. • Every object has attributes and behavior called operations. • The attributes are the data structures representing the properties of the objects.

  13. Encapsulation: • It is a mechanism that associates the code and data, it manipulates into a single unit. It is supported by class. • Encapsulation is the mechanism that binds together methods and the data, and keeps both safe from outside interference and misuse. • In an object-oriented language, functions and data may be combined in such a way that a "black box" is created. • The wrapping of data and functions into a single unit is known as encapsulation.

  14. Data Abstraction: • The technique of creating new datatype that are well suited to an application to be programmed is known as data abstraction. • The data types created by the process of data abstraction are called Abstract Datatype. 

  15. Inheritance: • Inheritance is the process by which an object of one class acquires the properties of objects of another class. • The class which inherits the properties from another class and the relation is called parent – child relation. • The parent class which gives its properties to another class is known as Base class. • The child class which inherits properties from parent class is known as derived class. • It allows the extension and reuse of existing code without having to rewrite the code from scratch. • The new derived class inherits the members of the base class and also adds its own.

  16. Ex: when the class B inherits the class A, the class B is called the derived class or sub class. • The class A is called the base or super class. • The class B has two parts. • Derived part: which is inherited from the base class A • Incremental part: which is the new code included in the class B.

  17. For example, Maruthi, sports cars and Benz are all types of cars. • In the object oriented language, sports cars, Maruthiand Benz are subclasses of the class car. • The class car is a "super class" (parent class or base class) of Maruthi, Benz, and sports cars. • Every subclass will inherit data (state) and functions (properties) from the super class. • The various types of cars such as Maruthi and Benz will share certain properties such as break, escalator, steering etc.

  18. The attribute once declared in the super class which are inherited by its subclasses, need not repeated. They can be accessed form any subclass unless they are private. • Only the methods of a class can access its private attributes. • The attributes which are declared as protected are accessible to subclasses.

  19. Single Inheritance: • refers to deriving a class from a single base class . Multiple Inheritance: • In this, the class is derived from more than one base class is known as multiple inheritance.

  20. Polymorphism: • Poly means many and morph means forms. So Polymorphism means many forms. • It allows a single name/operator to be associated with different operations depending on data passed on it. • The ability to use an operator or function in different ways or giving different meaning to the operators or functions is called polymorphism. • Poly refers many. That is a single function or an operator functioning or behaving in many ways depending upon the usage is called polymorphism. • Operator overloading and function overloading are the two kinds of polymorphism.

  21. EX: depending on the type of the arguments passed then it’s known as function overloading. • when an object/class has several methods with the same name that take different parameters: Calculate(int a, float b), Calculate(int a, int b), Calculate(float a, float b) • Here one of the three Calculate function is executed depending upon the arguments passed to it.

  22. Message Passing: • In an object oriented language, a message is sent to an object. • It is the process of invoking an operation on an object in response to a message, the corresponding method is executed in the object. • A message for an object is interpreted as a request for the execution of a function. • When message is received, the suitable function is invoked and result is generated in the object. • Ex: student.marks(rollNo) • It contains the name of the object, name of the function, information sent to the object. • In the above example : marks() is a message with the parameter rollNo as the information, student is an object. • Object have life time, created and destroyed, whenever necessary communication between objects can occur as long as they are alive.

  23. Extensibility: • it allows the extension of the functionality of the existing software components. Persistence : • The phenomenon where the object outlives the program execution time and exists between execution of program is known as persistence.  Genericity : • It allows the declaration of data items without specifying their exact datatype.

  24. Delegation: • Two most common techniques for reusing functionality in object oriented system are class inheritance and object composition. • In class inheritance we know that if the class B is derived from class A, then B is a kind of A. • The new approach to object composition says that an object can be a collection of many other objects and the relationship is called a has a relationship or containership. • Delegation is a way of making object composition as powerful as inheritance for reuse. • Here two objects are involved in handling the request: a receiving object delegates operations to its delegate. (just similar to subclasses sending requests to parent classes). • In some cases, inheritance and containership relations are serve the same purpose.

  25. A C++ program consists of a number of objects which communicate each other by calling one another’s member functions. • The member functions in C++ are called as methods. • Calling an object’s member function is referred to as sending a message to the object. • The object’s internal structure is totally hidden from the user and this property is called “ Data / information hiding ” or “ data encapsulation ”.

  26. In C++, both attribute (data) and methods (functions) are members of a class. The members are declared either as private or public. • Public members can be accessed by any function, private members can be accessed methods of the same class. • C++ has a special constructor function to initialize new instances and a destructor function to perform necessary clean up when an object is to be destroyed. • C++ provides 3 types of memory allocations for objects: • Static – pre allocated by the compiler – variable outside a function using static keyword. • Automatic- allocated on the stack – locals variables with in function. • Dynamic – allocated from a heap - explicit request from programmer.

  27. Differences structured programming approach object oriented programming approach Gives importance to data. Only the preferred set of methods can modify the data. Here data is not accessible to everyone. we can create a reusable component. they are divided into objects. • Gives importance to logic rather than data. • Data is not at all protected and can be modified by any anyone. • we cannot create reusable components • Large programs are divided to smaller programs known as functions.

  28. Differences structured programming approach object oriented programming approach objects can be mapped to a real world. For e.g. a program on Car can be written by creating a class called Car and having functions and data variables associated with it. • functions cannot be mapped to a real world object.

  29. Differences C++ programming language C Programming language C is an structured or procedural oriented programming language where the programs are written using several functions. Stdio.h files is included in the program for I/O. C doesn’t support inline and overloading of functions. • C++ is an object oriented programming language, programs are written using the classes and objects. • Stream objects for I/O i.e. iostream.h is used. C++ has stream-type objects like cin and cout • Inlining and overloading of functions.

  30. Differences C++ programming language C Programming language Only memory allocation functions like malloc, calloc are used. Do not support object-oriented programming. In C comments are enclosed in /* and */. Like C++ // cannot be used for comments. In C declaration statements must be the first statements in a block. • Storage operators new and delete. • Support for object-oriented programming through inheritance, polymorphism and encapsulation. • In C++ comments are enclosed in /* and */ and // • In C++, declaration statements can occur just anywhere in the code.

  31. Differences C++ programming language C Programming language Function and operator overloading is not possible in C. Functions with different type of arguments have to have different names. Operators cannot be redefined as in C++. • Function and operator overloading is possible in C++. Functions with different type of arguments can have same names. Operators can be redefined to perform different tasks.

  32. C++ was developed by BjarneStroustrup starting in 1979 at Bell Labs as an enhancement to the C programming language and originally named C with Classes. It was renamed as C++ in 1983.

  33. The C++ program • In C++, an action is referred to as an expression. • An expression terminated by a semicolon is referred to as a statement. • A smallest independent unit in a C++ program is a statement. • int book_count = 0; • This is a declaration statement. book_count is called as identifier or variable or symbolic variable or an object. • In C++, every program must contain a function called main (). • A C++ program begins execution with the first statement of main ().

  34. A function consists of four parts: • a return type • the function name • a parameter list • the function body (function definition) • The first three parts are collectively referred to as the function prototype. • The parameter list, enclosed within parenthesis, consists a comma separated list of zero or more parameters. • The function body is enclosed within a pair of curly braces. It consists of a sequence of program statements.

  35. A program source file’s name generally consists of two parts: a file name and extension. • .CPP is the file extension. • Part of the compiler’s job is to analyze the program for correctness. • Compiler cannot detect whether the meaning or the logic of the program is correct, but it can detect error in the program. • Two common forms of program errors are as follows: • Syntax error • Type error

  36. Syntax error • The programmer has made a grammatical error in the C++ program • Type error: • Each item of data in C++ has an associated type. • For e.g. the value of 10 is an integer. The word “hello” is string. If a function is expecting an integer argument but given a string then type error is signaled by the compiler.

  37. Comment: • The main purpose of the comment is the help the human readers of our program. • They help the person writing a program and anyone else who must read the source file or code, to understand what’s going on. • The compiler ignores the comments. Comments are helpful to describe apart of the code. There are two comment delimiters in C++: • Comments start with a double slash symbol (//) - Comments start with a double slash symbol (//) and terminate at the end of the line. This is mainly used for single line comments. Ex: // this is a program to add two numbers • The comment pair (/*, */) - The compiler treats everything falls between /* and matching */ as part of the comment. This is mainly used for multiple line comments. Ex: /* this is a program to add two numbers * /

  38. Input / Output • In C++ input and output is provided by the standard library known as iostream library. • Input from our terminal (standard input) is tied to a predefined iostream object cin. • Output to our terminal (standard output) is tied to a predefined iostream object cout. • Any program which uses cin and cout statements must include following statement. #include <iostream.h> • C++ uses the bit-wise left shift operator to perform output. • For e.g. cout <<”Hello world”; • The symbol << is called the insertion or put-to-operator. • More than one item can be displayed using a single cout object • For e.g. cout<< “age = “ <<age;

  39. C++ uses the bit-wise right shift operator to perform input operation. • Syntax: cin >> variable; • For e.g. cin>>age; • The symbol >> is called the extraction operator. • More than one item can be displayed using a single cout object • For e.g. cin>>name >>age;

  40. Basic structure of C++ program

  41. A sample C++ program • // program to display hello world // comment • #include<iostream.h> //pre processor directive • Void main() • { // function declaration • Cout<<“Hello world, SIT, Valachil, Mangalore”; • } • // end of the program

  42. The program (source code) is written in any available text editor. Then it is compiled to convert the machine code. • C++ program make use of libraries which contain the object code of standard functions. This code of all functions used in the program have to be combined with the program written by the programmer. • Some startup code is needed to produce an executable version of the program. • This process of combining all the needed object codes and startup code is called linking – which produces executable code.

  43. Scope resolution operator • C++ supports a mechanism to access a global variable from a function in which a local variable is defined with the same name as global variable. This is done using the scope resolution operator. • Syntax : ::global variable name • Ex: #include<iostream.h> • Int num=20; // global variable • void main() • { int num=30; // local variable • cout<< “local = ”<<num; • cout<< “global = ”<< ::num; //using scope resolution operator • cout<< “sum = ”<<::num+num; • } Output: Local = 30 global = 20 sum = 50

  44. manipulators • Manipulators are operators used to format the data display. • endl and setw are common used manipulators. • endl – indicates the end of line. Further content will be displayed in the next line. • setw used to specify a field width to the data so that it is right justified leaving enough spaces to its right if number of characters are less. • Ex: cout<<sum<<endl; • Cout<<setw(5)<<sum;

  45. DATA TYPES

  46. Data types • Data is the smallest unit of information that the computer manipulates. • The type of data being manipulated in the computer defined the data type. • Basic data types are integer, floating point character. • C++ supports both basic and derived data types. • Two more data types bool and wchar_t are added by ANSI C++.

  47. C++ Data Types Array Function Pointer Reference Derived Type Structure Union Class Enumeration User-defined type Built-in Type Integral Type Void Floating Type float double int char

  48. Data Types It describes the characteristics of the data. There are different types- Primary/ Fundamental Data type: integer (int) character (char) floating point (float) double-precision floating point (double)

  49. There are five basic data types: • char • int • float • double • void • ANSI C++ adds two more: • bool Boolean value • wchar_t wide character

  50. The wchar_t Type Specifier • The wchar_t type specifier is an integral type that has enough storage to represent a wide character literal. • A wide character literal is a character literal that is prefixed with the letter L, for example L'x'

More Related