Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming (C++)

Similar presentations


Presentation on theme: "Object Oriented Programming (C++)"— Presentation transcript:

1 Object Oriented Programming (C++)
Lecture 1: A Tour of C++

2 Main Contents What is C++ Procedural programming Modular programming
Data abstraction Object-Oriented Programming The presentation is split up in 3 sections. Section 1 is contains some background information on C++ to, a short comparison to C and then an introduction to some basics that might be useful for the examples.

3 History of C++ Developed by Dr. Bjarne Stroustrup at AT&T Bell labs in the early 80’s Originally called C with Classes 1985 First external C++ release 1990 first Borland C++ release, The Annotated C++ Reference Manual 1995 Initial draft standard released 1997 Formally approved international C++ standard is accepted – ISO/ANSI C++ The C language was developed mainly by Dennis Ritchie from Bell Labs in the Early ’70s as a programming language used to develop the Unix operating system. Many implementations of the C language followed and only in 1989 was the ANSI standard for C published. In the early ’80s, Bjarne Stroustrup, also from Bell Labs, started development of a language based on C but which included Object Orientated concepts from other languages such as Simula67. This was known as “C with Classes”. In October 1985 the first commercial release of the language appeared together with the first edition of the book: “The C++ Programming Language” by Bjarne Stroustrup. In November 1997, the ANSI standard for C++ was published. Nowadays, C++ is the most widely used programming language in the world to develop applications. The reasons include its portability, flexibility, code reuse and quality.

4 C versus C++ C is the base language for C++. It is: versatile(通用性)
low-level excellent for system programming runs everywhere and on everything (transplant) C has evolved, partly under the influence of C++. Example, the use of f (void). “Good C programs tend to be C++ programs,” ---- Bjarne Stroustrup. For example, every program in The C programming language is a C++ program. As we saw, C++ was developed from C. C versus C++ Question: Is C++ the best language? (Better than C?) This sometimes become a political play ball which I don’t want to become involved in. C++ offers certain advantages over C which we will be presented as we progress. 2 things to keep in mind however: A language should be used to solve the particular problem faced as well as the environment. For example, you won’t write a database application in Fortran anymore than you will try to manipulate matrices in Cobol. Another example where the environment is crucial is for instance Java in an embedded solution as oppose to C or C++. For programming in general, a bad coding style will result in a bad program, no matter what language is being used. The transition from C to C++ does not only require the developer to learn the new language features. More important is the different view that has to be taken when analyzing a problem and designing a solution. C++ is bridging the gap from a pure procedural way (algorithms) to an object orientated analysis of the problem domain. Remember that we are not only talking of implementing an algorithm (that is usually the easy part). The scope of an environment is usually larger than just implementing an algorithm. There are also interactions between other systems, software etc. Thus, thought has to be put into how this algorithm fits into the grand structure. It is believed that C++ allows a more natural and effective way to deal with this problem. Some additional ideas on programming and software engineering. Programming – that act of writing code and creating a program Software engineering – including programming but also analysis, design, implementation. Size of projects – as technology develops, the size and scope of project increased a lot. These days, it is very seldom that only one programmer works on a complete application or project but instead a team of developers. Programming and software engineering is very much a combination of art and science. The artistic part has to do with the fact that a solution to a problem must be found. (Creative part). You need to analyze the problem, design the solution and eventually implement this. Usually there are many solutions to the same problem. Some better than others. The science part comes in as there exists many problems that can be modeled in terms of mathematics etc.

5 What is C++? C++ is a general-purpose programming language with a bias towards system programming that Is a better C, Supports data abstraction, Supports object-oriented programming, and Supports generic programming Some of the claimed advantages of C++ include: Faster development time due to code reuse Creating and using new data types is easier than in C Memory management is easier and more transparent Stricter syntax and type checking resulting in less bugs Data hiding is easier to implement Object Orientated concepts in C++ allows direct coding form an OO Analysis and Design (UML) The above points can be debated as many of these can be implemented in C with “fancy tricks”. The point is, C++ cater for this and more as part of the syntax.

6 Procedural Programming
Decide which procedures you want; use the best algorithms you can find. C++ support for procedural programming Variables and arithmetic Tests and loops Pointers and arrays C++ is known as a hybrid-language as oppose to a pure OO-Language. The reason being the fact that you can code as in C, (in a procedural way) or in a pure OO way or a mix of both. To be regarded as an Object Orientated language, four fundamental concepts must be included: Encapsulation (Data hiding by means of classes: private, protected and public) Only member functions can access private member data Inheritance Polymorphism Ability to be dynamic (The concept of objects which can be instantiated, communicate with each other via messages.)

7 Typical example: //C++程序:MyMax.cpp #include <iostream.h>
float max(float a,float b) { float c; if(a>b) c=a; else c=b; return c; } void main() { float x,y,z; cout<<"输入两个数:\n"; cin>>x>>y; z=max(x,y); cout<<"最大数是:"; cout<<z<<'\n'; } The following list mentions most of the obvious differences between C++ and C. C++ is a superset of C. You can compile a C program in C++ but not vice-versa. Namespaces – symbols are defined in a larger context to avoid conflicts In C++ you can declare a variable at any point in the code Commenting - // is only applicable to a line, You can still use /* */ pairs. The use of // is recommended In C it was custom to initialize pointers to NULL, in C++ all zero values are coded as 0. C++ uses much stricter type checking. For instance, in C++ you always have to give a prototype declaration for a function definition. Furthermore, the prototype must match exactly the function definition. If not, the compiler will give an error. In C, this was not necessary and was a source of many errors.

8 Variables and arithmetic
fundamental types: bool // Boolean, possible values are true and false char // character, eg: ’a’, ’z’, and ’9’ int // integer, eg: 1, 42, and 1216 double // double-precision floating-point number, eg: 3.14 and arithmetic operators // plus, both unary and binary // minus, both unary and binary * // multiply / // divide % // remainder C++ introduces the bool (boolean) data type which can only hold the values ‘true’ or ‘false’. Cast Static_cast – used to convert one type to acceptable other type Eg. intVar = static_cast<int> (12.45) Const_cast – used to negate const-ness of variable function (char* s) and const hello[] = “Hello world!”. The statement function(hello) produces warning: “passing `const char *' as argument 1 of `fun(char *)' discards const”. Instead use function(const_cast<char *>(hello)) Reinterpret_cast – used to access individual bytes double doubleVar; reinterpret_cast<char *>(&doubleVar) dynamic_cast – used in the context of polymorphism. Using cast operators are dangerous as it suppresses the normal type checking mechanism of the compiler. If it has to be used, document it well inside the code.

9 Variables and arithmetic (cont.)
comparison operators: == // equal != // not equal < // less than > // greater than <= // less than or equal >= // greater than or equal C++ performs all meaningful conversions between the basic types so that they can be mixed freely. C++ introduces the bool (boolean) data type which can only hold the values ‘true’ or ‘false’. Cast Static_cast – used to convert one type to acceptable other type Eg. intVar = static_cast<int> (12.45) Const_cast – used to negate const-ness of variable function (char* s) and const hello[] = “Hello world!”. The statement function(hello) produces warning: “passing `const char *' as argument 1 of `fun(char *)' discards const”. Instead use function(const_cast<char *>(hello)) Reinterpret_cast – used to access individual bytes double doubleVar; reinterpret_cast<char *>(&doubleVar) dynamic_cast – used in the context of polymorphism. Using cast operators are dangerous as it suppresses the normal type checking mechanism of the compiler. If it has to be used, document it well inside the code.

10 Tests and loops bool accept ( ) {
cout << "Do you want to proceed (y o r n )?\ n "; // write question char answer = 0 ; cin >> answer ; // read answer if (answer == ´y ´) return true ; return false ; } In C the declaration ‘extern function()’ means the parameter list is not prototyped. You can call this function with any number and type of arguments and compiler does not perform type checking which is dangerous. To declare a function with empty parameter list you must use ‘extern function(void)’. In C++, the two definitions are equivalent meaning the function does not take any arguments. Calling the function with an argument will result in an error. To use standard C functions in a C++ application, they must be declared as C functions:    extern “C” void *xmalloc(unsigned size) extern “C” { //C-declarations go here } #include <myheader.h> //myheader.h declares C functions In C++ it is possible to perform function overloading. Function overloading is the process of using the same function name for two ‘different’ actions. The name must be the same but the parameter list must differ in terms of 1) the number of parameters, 2) type of parameters, 3) const-ness

11 cin >> answer ; // read answer switch (answer ) case ´y ´:
bool accept3( ) { int tries = 1 ; while (tries < 4 ) { cout << "Do you want to proceed (y o r n )?\ n "; // write question char answer = 0 ; cin >> answer ; // read answer switch (answer ) case ´y ´: return true ; case ´n ´: return false ; default : cout << "Sorry , I don’ t understand that .\ n "; tries = tries+ 1 ; } } cout << "I ´ll take that for a no .\ n "; return false ; } It is possible in C++ to provide default arguments when defining a function. When the function is called with no arguments, the compiler will supply the arguments. eg. void two_ints(int a = 1, int b = 4) void main() { two_ints(); // arguments: 1, 4 two_ints(20); // arguments: 20, 4 two_ints(20, 5); // arguments: 20, 5 } The keyword ‘typedef’ is still valid in C++ but not required anymore when declaring structures. struct somestruct int a; double d; char string[80]; }; Somestruct what; what.d = ; In C++, functions can be declared as part of a structure. More information will follow later. The default return value for functions in C is integer if non is specified. In C++, you have to specify the return value otherwise the compiler will give a warning (void for no return value). You can assign any type to the void pointer, but before using it you must cast it to a data type.

12 Pointers and arrays An array can be declared like this:
char v [1 0 ]; // array of 10 characters Similarly, a pointer can be declared like this: char * p ; // pointer to character A pointer variable can hold the address of an object of the appropriate type: p = &v[3 ]; // p points to v’s fourth element Consider copying ten elements from one array to another: void another _ function ( ) { int v1 [1 0 ]; int v2 [1 0 ]; / / ... for (int i=0 ; i<1 0 ; ++i ) v1[i ]=v2[i ]; } The C++ IO-stream library still makes use of the stream concept, but this library is a redesign which makes use of classes. It essentially provides the same functionality as the file-based I/O as in C but you get more in terms of type safety, extensibility and a clean design. The library is organized in a hierarchical set of classes. At the top level, a basic class ios_base is defined from where all other classes are inherited. To understand the details of the IO-streams library, requires knowledge of class concepts such as inheritance, composition, polymorphism etc. which will only be covered later. Therefore, brief examples will follow of how to use the basic input/output features that are provided by this library in a C++ program.

13 Modular Programming Decide which modules you want; partition the program so that data is hidden within modules. Stack module C++ input is primarily based on the istream class. This class defines the basic operators and members to extract information from streams. The extraction operator >>, and members like istream::read() are provided. The class istream, offering the basic facilities for doing input; The class ifstream, allowing us to open files for reading (comparable to C's fopen(filename, "r")); The class istringstream, allowing us to read information from text that is not stored on files (streams) but in memory (comparable to C's sscanf() function). To use these classes directly you should include the appropriate header file. cin is in fact an instance of the class istream. cin is defined in the class iostream, which means that you need to include <iostream> if you want to use cin directly.

14 Separate compilation C++ support C’s notion of separate compilation. This can be used to organize a program into a set of semi-independent fragments. Example: stack.h namespace Stack { void push(char); char pop(); } C++ out is primarily based on the ostream class. This class defines the basic operators and members to insert information into streams. The insertion operator <<, and members like ostream::write() are provided. The class ostream, offering the basic facilities for doing output; The class ofstream, allows to open files for writing (comparable to C's fopen(filename, “w")); The class ostringstream, allows to write information to memory rather than files(comparable to C's sprintf() function). To use these classes directly you should include the appropriate header file. Like cin, cout an instance of the class ostream. cout is defined in the class iostream, which means that you need to include <iostream> if you want to use cout directly.

15 void Stack::push(char c) v[top++] = c; } char Stack::pop()
stack.c #include "Stack.h" namespace Stack { const int max_size = 200; char v[max_size]; int top = 0; } void Stack::push(char c) v[top++] = c; } char Stack::pop() return v[--top]; } Example 1 is demonstrates how to read in variables of different types from the command line and write them again to screen. Example2 demonstrates how some basic formatting is done using c++ stream class.

16 #include <iostream.h> void main( ) { Stack::push('s');
user.c #include " stack.h" #include <iostream.h> void main( ) { Stack::push('s'); if ( Stack::pop() != 's' ) cout<< "Impossible!\n"; else cout<< "Good!\n"; } Example 1 is demonstrates how to read in variables of different types from the command line and write them again to screen. Example2 demonstrates how some basic formatting is done using c++ stream class.

17 Data Abstraction Decide which types you want; provide a full set of operations for each type. Modules Defining Types (eg:Stack) User-Defined Types Concrete Types Abstract Types

18 User-Defined Types Decide which type you want and provide a full set of operations for each type. class complex { private: double real, imag; public: complex(double r,double i) { real=r; imag=i; } double abscomplex( ); }; A big part of programming, deals with manipulating strings. C++ introduces the string class type. This class contains many member functions that can be used to manipulate strings. In order to use the string class, you must include the header file <string>. The general syntax when using strings is stringVar.operation(argumentlist).

19 double complex :: abscomplex() { double t; t=real*real+imag*imag;
return sqrt(t); } void main() { complex A(1.1,2.2), B(3.2, 0.3); //定义类的对象A时调用构造函数 complex C=A-B; cout<<” abs of complex A=”<<A.abscomplex()<<endl; Refer to example5.cpp for some brief examples of how to use strings. The available member functions in the C++ string class is quite large. When manipulating strings, refer to the documentation for C++ strings to see if there is already a function that will perform a given task. Chances are good there is one or some others that will help you accomplish your task.

20 Abstract Types Sole purpose is to provide a base class for other classes by Declaring one or more virtual functions as “pure” by initializing the function to zero. class Stack { public: virtual void push(char c) = 0; virtual char pop() = 0; class Underflow {}; // used as exception class Overflow {}; // used as exception }; The Definition of Object Orientated Programming: Everything is defined as an object and these objects communicate with each other by way of messages. The focus is thus more on the data itself than the procedure of how to solve a problem. It is more natural way to model real world problems.

21 Object Oriented Programming
Object Orientation Programming is called OOP OOP Encapsulates data (attributes) and functions (behavior) into packages called classes Data and functions closely related Unit of C++ programming: the class A class is like a student – reusable Objects are instantiated (created) from the class For example, Xiao Ming is an instance of a “student class” C programmers concentrate on functions In C, every client programmer are free to access all members of a struct. Furthermore, as seen in the earlier example, no one forces to call the initialize and cleanup functions, although they are very important. There are two main reasons for controlling access to members. You might want to hide the internal mechanisms of the library from the user (many reasons: intellectual property, convenience, safety) You can change the internal workings of a library without affecting the interface. Refer to example8.cpp

22 Classes and Objects Classes have variables which describe the current state of the object. Changing the state of an object is done through the class functions. Every time we declare an object we create a new instance of the class. Public – anybody have access to these members. Private – only the member functions of the structure have access to the private member functions. Friend functions. If you need to specifically grant access to a private member of a structure to a function which is not part of the structure, you can accomplish this by declaring the function as a friend inside the structure. Refer to example9.cpp We now convert the cppDArray struct to c++ class. Refer to example10.cpp in /CPPCLASS

23 Class Hierarchies Definition:
The inheritance mechanism provides a solution. Definition: It is a mechanism which supports arrangement classification in C++ programming. And it allows the programmer to explain the class in detail based on keeping the characters of original class. New classes created from existing classes Absorb attributes and behaviors. So far we have seen a typical C library, some of the issues related to it. We then converted it to a C++ style library. Introduced encapsulation and then implementation hiding. This already is a big step towards safer and easier use of code by client programmers. With this in mind, C++ allows more built-in features to make programs even more safer. Two of these issues are initialization and cleanup. As pointed out earlier, memory management can be tricky in C and are usually the source of many errors. Client programmers don’t know how to initialize a struct. If they must do it themselves. Often no initialize functions exist etc. In our example special care has to be taken to explicitly call the initialization and cleanup functions of the C-library. The way C++ handles this is with the help of a constructor and destructor. Refer to example11.cpp in /CONSTRUCT The name of the constructor is the same of that of the class. The constructor acts like any other function so you can give arguments to it. One thing to note is that the constructor does not contain a return value. At least one constructor per class must be defined. You may have more than one. The constructor without any arguments are generally known as the default constructor. Destructors is the function that performs all the cleanup. They have the same name as the constructor with the prefix ~. You do not have to explicitly call the destructor, the compiler takes care of this when the object goes out of scope.

24 Point where() { return center; }
class Shape { public: Point where() { return center; } void move(Point to) { center = to; draw();} virtual void draw() = 0; virtual void rotate(int angle) = 0; private: Point center; Color col; //... }; Function overloading is a good way to make a program more readable. Function overloading is when the same name is given to a function that has more or less the same functionality. This is also the criteria to use when considering overloading functions. The distinguishing characteristic is the argument list, whether it is the number of arguments or the type of the arguments. For example: void func(), void func(int intVar), void func(float fVar), void func(char cVar), void func(int inVar, float fVar) are all overloaded functions. The compiler can figure out which function to call because the argument list is unique in terms of type and/or number of arguments. Function overloading are typically used primarily when you need to perform the same functionality but with different types, for example when you perform an operation on integers or floating point values. Another place where overloading functions are used is the constructor of classes. The reason here is that you might want to initialize a class in different ways depending on certain conditions and circumstances. For example, the initialization can be done by reading from a file or default initialization as hard coded in a program. Refer to example12.cpp. /OVERLOAD As with overloading functions, default arguments is a convenience to programmers. It the example above, calling the function with func(5) efectively means func(5, 0.0). However if you make the call func(5, 6.7). The value for y is 6.7 in the function. Two things to keep in mind when defining default arguments: Only trailing arguments may be defaulted Following from 1) once a default argument is used, all subsequent arguments in the list must be defaulted

25 class Circle : public Shape { public: void draw() { /* ... */ }
void rotate(int) {} private: int radius; }; void rotate_all(vector<Shape*>& v, int angle) for (int i=0; i<v.size(); ++i) v[i]->rotate(angle); } Although the c-language also has a const keyword, the meaning and scope in C++ is slightly different. The first motivation for the use of const was to replace the #define declarations found in many C programs. The problem with the #define is that it only exists during the preprocessor phase. The preprocessor simply does text replacement where the name is used in the code. The compiler knows nothing of the definition and therefore cannot perform type checking. This can sometimes lead to subtle errors in code. Therefore, the code: #define BUFFSIZE 100 should be rather replaced by const int bufsize = 100; You can place this definition in a header file and distribute it to translation units by including the header file. If you initialize a variable only at runtime but you know the value will not change then you can define it with a const keyword: const char c = cin.get(). Now if you try to change the value of the variable at some point in your code, the compiler will complain.

26 Now the programming paradigm is:
Decide which classes you want; provide a full set of operations for each class; make commonality explicit .

27 Generic Programming Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures. Generic container Generic algorithms Constants have more applications in function arguments and return values, class members and member functions. This however is outside the scope of this course and the reader is referred to the source. The volatile keyword is closely associated with const. Defining a keyword as volatile tells the compiler not to assume anything regarding the value. In other words, the value could have changed by another process, agent etc. Therefore no optimization is done by the compiler. This is usually used when communicating with hardware.

28 Containers Templates provide direct support for generic programming, that is, programming using types as parameters. The C++ template mechanism allows a type to be a parameter in the definition of a class or function. In short, the variable type is a parameter. C allows you to define macros in code to makes the code more efficient. What happens behind the scenes is that the preprocessor substitutes all references to the macro in the code, with the actual source. There are 2 problems in C++ however. A macro looks like a function call but doesn’t always act like one. This can introduce subtle bugs in a program which can be difficult to track down. Secondly, the preprocessor has no permission to access class member data. Thus, macros cannot be used as class member functions The use of inline functions should be used with care: As mentioned, inline functions are expanded in place and if the function is quite big this might bloat the code and make it inefficient again. Places to avoid inline functions are: Recursive functions Functions containing loops such as for(,,) and while() The function size is too large The benefit from inline functions come because the overhead of making function call is avoided. Refer to exampl13.cpp in /INLINE.

29 Generic Algorithms The C++ standard library provides a variety of containers, and users can write their own. Thus, we find that we can apply the generic programming paradigm once more to parameterize algorithms by containers. References is special kind of pointer. It is a pointer that points to another variables storage. References is mostly used in passing arguments into and from functions. When passing a reference to a function. The address of a storage location is passed to the function. What happens is that the actual variable you are referring to are manipulated. (Unlike when you use normal argument passing where a copy of the variable is made.) This allow for cleaner syntax than using pointers. Returning a reference is the same. You should however take care that the memory that exists when the function exists still exists otherwise the you’ll be referring to unknown memory. It should become habit that for the majority of functions, passing by const-reference should be the norm. The value of this will be seen when user defined functions are being past to functions.

30 Advice Don’t panic! All will become clear in time.
You don’t have to know every detail of C++ to write good programs. Focus on programming techniques, not on language features. When you pass any value to a function by value, the compiler makes a local copy of the variable inside the function. However, for user defined objects (Classes etc.) this is not possible because there are problems when the compiler performs a bitwise-copy. Therefore, you need to define your own copy function. The reason it is also a constructor is because you are creating a new object. Secondly, you use references because you construct a new object from an existing one. The details is however outside of the scope and I refer you to the source for further reading.

31 Homework make a program to reversely output a num. eg: input 123,output 321。


Download ppt "Object Oriented Programming (C++)"

Similar presentations


Ads by Google