CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 32 Thanks for Lecture Slides: C How to Program by Paul Deital &

Slides:



Advertisements
Similar presentations
21-Aug-14 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Advertisements

Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Introduction to C++CS-2303, C-Term Introduction to C++ CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
C++ fundamentals.
Introduction to C++ Systems Programming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
The Java Programming Language
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Basic Object-Oriented Concepts – towards implementation CS3340.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Basic Object-Oriented Concepts
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Object-Oriented Programming (OOP) and C++
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Chapter 15 - C++ As A "Better C"
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Systems Programming.
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Classes and Objects.
Introduction to C++ Programming
Variables have attributes
Chapter 15 - C++ As A "Better C"
Java Programming Language
Capitolo 1 – Introduction C++ Programming
Classes and Methods 15-Aug-19.
Presentation transcript:

CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 32 Thanks for Lecture Slides: C How to Program by Paul Deital & Harvey Deital 6Ed.

Difference between; Programming in C and C++ 2

C++ Improves on many of C's features Has object-oriented capabilities Increases software quality and reusability Developed by Bjarne Stroustrup at Bell Labs Called "C with classes" C++ (increment operator) - enhanced version of C Superset of C Can use a C++ compiler to compile C programs Gradually evolve the C programs to C++ 3

A Simple Program: Adding Two Integers File extensions C files:.c C++ files:.cpp (which we use),.cxx,.C (uppercase) Differences C++ allows you to "comment out" a line by preceding it with // For example: // text to ignore - input/output stream header file Return types - all functions must declare their return type C does not require it, but C++ does Variables in C++ can be defined almost anywhere In C, required to defined variables in a block, before any executable statements 4

A Simple Program: Adding Two Integers (II) Input/Output in C++ –Performed with streams of characters –Streams sent to input/output objects Output – std::cout - standard output stream (connected to screen) – << stream insertion operator ("put to") – std::cout << "hi"; Puts "hi" to std::cout, which prints it on the screen Input – std::cin - standard input object (connected to keyboard) – >> stream extraction operator ("get from") – std::cin >> myVariable; Gets stream from keyboard and puts it into myVariable 5

A Simple Program: Adding Two Integers (III) std::endl –"end line" –Stream manipulator - prints a newline and flushes output buffer Some systems do not display output until "there is enough text to be worthwhile" std::endl forces text to be displayed using statements –Allow us to remove the std:: prefix –Discussed later Cascading –Can have multiple > operators in a single statement std::cout << "Hello " << "there" << std::endl; 6

C++ Standard Library C++ programs built from –Functions –Classes Most programmers use library functions Two parts to learning C++ –Learn the language itself –Learn the library functions Making your own functions –Advantage: you know exactly how they work –Disadvantage: time consuming, difficult to maintain efficiency and design well 7

Header Files Header files –Each standard library has header files Contain function prototypes, data type definitions, and constants –Files ending with.h are "old-style" headers User defined header files –Create your own header file End it with.h –Use #include "myFile.h" in other files to load your header 8

Header Files 9

10

Header Files 11

Inline Functions Function calls Cause execution-time overhead Qualifier inline before function return type "advises" a function to be inlined Puts copy of function's code in place of function call Speeds up performance but increases file size Compiler can ignore the inline qualifier Ignores all but the smallest functions inline double cube( const double s ) { return s * s * s; } Using statements By writing using std::cout; we can write cout instead of std::cout in the program Same applies for std::cin and std::endl 12

13

References and Reference Parameters Call by value Copy of data passed to function Changes to copy do not change original Call by reference Function can directly access data Changes affect original Reference parameter alias for argument –Use & void change(int &variable) { variable += 3; } Adds 3 to the original variable input – int y = &x Changing y changes x as well 14

References and Reference Parameters (II) Dangling references Make sure to assign references to variables If a function returns a reference to a variable, make sure the variable is static Otherwise, it is automatic and destroyed after function ends Multiple references Like pointers, each reference needs an & int &a, &b, &c; 15

Default Arguments and Empty Parameter Lists If function parameter omitted, gets default value Can be constants, global variables, or function calls If not enough parameters specified, rightmost go to their defaults Set defaults in function prototype int myFunction( int x = 1, int y = 2, int z = 3 ); 16

Default Arguments and Empty Parameter Lists (II) Empty parameter lists In C, empty parameter list means function takes any argument In C++ it means function takes no arguments To declare that a function takes no parameters: Write void or nothing in parentheses Prototypes: void print1( void ); void print2(); 17

Unary Scope Resolution Operator Unary scope resolution operator ( :: ) Access global variables if a local variable has same name Instead of variable use ::variable static_cast (variable) Creates a copy of variable of type newType Convert ints to floats, etc. Stream manipulators Can change how output is formatted setprecision - set precision for float s (default 6 digits) setiosflags - formats output setwidth - set field width Discussed in depth in Chapter 21 18

Function Overloading Function overloading: Functions with same name and different parameters Overloaded functions should perform similar tasks Function to square int s and function to square float s int square( int x) {return x * x;} float square(float x) { return x * x; } Program chooses function by signature Signature determined by function name and parameter types Type safe linkage - ensures proper overloaded function called 19

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 //or template 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 int s Can use float, double, long... 20

Basic Object-Oriented Concepts

22 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains both data and methods that manipulate that data An object is active, not passive; it does things An object is responsible for its own data But can expose that data to other objects CSC 141 Introduction to computer Programming

23 Concept: An object has state An object contains both data and methods that manipulate that data The data represent the state of the object Data can also describe the relationships between this object and other objects Example: A CheckingAccount might have A balance (the internal state of the account) An owner (some object representing a person) CSC 141 Introduction to computer Programming

24 Example: A “Rabbit” object You could (in a game, for example) create an object representing a rabbit It would have data: How hungry it is How frightened it is Where it is And methods: eat, hide, run, dig CSC 141 Introduction to computer Programming

25 Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields, or variables The class describes those fields An object may have methods The class describes those methods A class is like a template, or cookie cutter You use the class’s constructor to make objects CSC 141 Introduction to computer Programming

26 Concept: Classes are like Abstract Data Types An Abstract Data Type (ADT) bundles together: some data, representing an object or "thing" the operations on that data The operations defined by the ADT are the only operations permitted on its data Example: a CheckingAccount, with operations deposit, withdraw, getBalance, etc. Classes enforce this bundling together If all data values are private, a class can also enforce the rule because its defined operations are the only ones permitted to access the data CSC 141 Introduction to computer Programming

27 Example of a class class Employee { // Fields private String name; //Can get but not change private double salary; // Cannot get or set // Constructor Employee(String n, double s) { name = n; salary = s; } // Methods void pay () { System.out.println("Pay to the order of " + name + " $" + salary); } public String getName() { return name; } // getter } CSC 141 Introduction to computer Programming

28 Approximate Terminology instance = object field = instance variable method = function sending a message to an object = calling a function These are all approximately true CSC 141 Introduction to computer Programming

29 Concept: Classes form a hierarchy Classes are arranged in a treelike structure called a hierarchy The class at the root is named Object Every class, except Object, has a superclass A class may have several ancestors, up to Object When you define a class, you specify its superclass –If you don’t specify a superclass, Object is assumed Every class may have one or more subclasses CSC 141 Introduction to computer Programming

30 Example of (part of) a hierarchy A FileDialog is a Dialog is a Window is a Container Container PanelScrollPane Window DialogFrame FileDialog CSC 141 Introduction to computer Programming

31 C++ is different In C++ there may be more than one root –but not in Java! In C++ an object may have more than one parent (immediate superclass) –but not in Java! Java has a single, strict hierarchy CSC 141 Introduction to computer Programming

32 Concept: Objects inherit from superclasses A class describes fields and methods Objects of that class have those fields and methods But an object also inherits: the fields described in the class's superclasses the methods described in the class's superclasses A class is not a complete description of its objects! CSC 141 Introduction to computer Programming

33 Example of inheritance class Person { String name; int age; void birthday () { age = age + 1; } class Employee extends Person { double salary; void pay () {...} } Every Employee has name and age fields and birthday method as well as a salary field and a pay method. CSC 141 Introduction to computer Programming

34 Concept: Objects must be created int n; does two things: It declares that n is an integer variable It allocates space to hold a value for n For a primitive this is all what is required. Employee secretary; also does two things It declares that secretary is type Employee It allocates space to hold a reference to an Employee For an object, this is not all that is needed secretary = new Employee ( ); –This allocate space to hold a value for the Employee –Until you do this, the Employee is null CSC 141 Introduction to computer Programming

35 Notation: How to declare and create objects Employee secretary; // declares secretary secretary = new Employee (); // allocates space Employee secretary = new Employee(); // does both But the secretary is still "blank" ( null ) secretary.name = "Adele"; // dot notation secretary.birthday (); // sends a message CSC 141 Introduction to computer Programming

36 Notation: How to reference a field or method class Person {age = age + 1;} Outside a class, you need to say which object you are talking to if (ahmed.age < 60) ahmed.birthday (); If you don't have an object, you cannot use its fields or methods! CSC 141 Introduction to computer Programming

37 Concept: this object class Person {this.age = this.age + 1;} this is like an extra parameter to the method we usually don't need to use this CSC 141 Introduction to computer Programming

38 Concept: A variable can hold subclass objects Suppose B is a subclass of A A objects can be assigned to A variables B objects can be assigned to B variables B objects can be assigned to A variables, but A objects can not be assigned to B variables o Every B is also an A but not every A is a B You can cast: bVariable = (B) aObject; CSC 141 Introduction to computer Programming

39 Example: Assignment of subclasses class Dog {... } class Poodle extends Dog {... } Dog myDog; Dog rover = new Dog (); Poodle yourPoodle; Poodle fifi = new Poodle (); myDog = rover; // ok yourPoodle = fifi; // ok myDog = fifi; //ok yourPoodle = rover; // illegal yourPoodle = (Poodle) rover; //runtime check CSC 141 Introduction to computer Programming

40 Concept: Methods can be overridden So birds can fly. Except penguins. class Bird extends Animal { void fly (String destination) { location = destination; } class Penguin extends Bird { void fly (String whatever) { } } CSC 141 Introduction to computer Programming

41 Concept: Don't call functions, send messages Bird someBird = pingu; someBird.fly ("South America"); Did pingu actually go anywhere? You sent the message fly(...) to pingu If pingu is a penguin, he ignored it Otherwise he used the method defined in Bird You did not directly call any method You cannot tell, without studying the program, which method actually gets used The same statement may result in different methods being used at different times CSC 141 Introduction to computer Programming

42 Concept: Constructors make objects Every class has a constructor to make its objects Use the keyword new to call a constructor secretary = new Employee ( ); You can write your own constructors; but if you don’t, C++ provides a default constructor with no arguments It sets all the fields of the new object to zero If this is good enough, you don’t need to write your own The syntax for writing constructors is almost like that for writing methods CSC 141 Introduction to computer Programming

43 Syntax for constructors Do not use a return type and a name; use only the class name You can supply arguments Employee (String theName, double theSalary) { name = theName; salary = theSalary; } CSC 141 Introduction to computer Programming

44 Internal workings: Constructor chaining If an Employee is a Person, and a Person is an Object, then when you say new Employee () The Employee constructor calls the Person constructor The Person constructor calls the Object constructor The Object constructor creates a new Object The Person constructor adds its own stuff to the Object The Employee constructor adds its own stuff to the Person CSC 141 Introduction to computer Programming

45 Concept: Classes can have fields and methods Usually a class describes fields (variables) and methods for its objects (instances) –These are called instance variables and instance methods A class can have its own fields and methods –These are called class variables and class methods There is exactly one copy of a class variable, not one per object Use the special keyword static to say that a field or method belongs to the class instead of to objects CSC 141 Introduction to computer Programming

46 Example of a class variable class Person { String name; int age; static int population; Person (String name) { this.name = name; this.age = 0; population++; } CSC 141 Introduction to computer Programming

47 Recommendations : Restrict access Always, always strive for a narrow interface Follow the principle of information hiding: the caller should know as little as possible about how the method does its job the method should know little or nothing about where or why it is being called Make as much as possible private Your class is responsible for it’s own data; don’t allow other classes to screw it up! CSC 141 Introduction to computer Programming

48 Advice: Use setters and getters This way the object maintains control Setters and getters have conventional names: set DataName, get DataName, is DataName (booleans only) class Employee extends Person { private double salary; private boolean male; public void setSalary (double newSalary) { salary = newSalary; } public double getSalary () { return salary; } public boolean isMale() { return male; } } CSC 141 Introduction to computer Programming

49 Kinds of access C++ provides four levels of access: – public : available everywhere – protected : available within the package (in the same subdirectory) and to all subclasses –[default]: available within the package – private : only available within the class itself CSC 141 Introduction to computer Programming