CSC 270 – Survey of Programming Languages C++ Lecture 3 - Introducing Objects.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Operator overloading redefine the operations of operators
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Wednesday, 10/2/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 10/2/02  QUESTIONS (on HW02 – due at 5 pm)??  Today:  Review of parameters  Introduction.
Introduction to Computer Programming Classy Programming Techniques II: Writing Objects.
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.
1 Object-Oriented Programming Using C++ CLASS 27.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
Structured Programming Instructor: Prof. K. T. Tsang Lecture 13:Object 物件 Oriented 面向 Programming (OOP)
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CSC 270 – Survey of Programming Languages C++ Lecture 4 – More on Writing Classes.
Agenda Object Oriented Programming Reading: Chapter 14.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Chapter 10 Inheritance and Polymorphism
Object Oriented Programming (OOP) Lecture No. 8. Review ► Class  Concept  Definition ► Data members ► Member Functions ► Access specifier.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
C++ Lecture 1 Friday, 4 July History of C++ l Built on top of C l C was developed in early 70s from B and BCPL l Object oriented programming paradigm.
C++ Classes and Data Structures Jeffrey S. Childs
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
1 CSC241: Object Oriented Programming Lecture No 02.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Class Method Read class Student { private: string id; string firstName, lastName; float gpa; public: // Will the method change any data members? // Yes!
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
OOP Basics Classes & Methods (c) IDMS/SQL News
Fundamental Programming Fundamental Programming Introduction to Functions.
Class & Objects C++ offers another user-defined data type known class which is the most important feature of the object-oriented programming. A class can.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 05: Object Oriented Programming:2014 Object-Oriented Programming in C++ Exception.
1 C++ Classes and Data Structures Course link…..
Chapter 12 Classes and Abstraction
Lecture 3 (UNIT -1) SUNIL KUMAR CIT-UPES.
Chapter 1.2 Introduction to C++ Programming
This technique is Called “Divide and Conquer”.
Classes and Data Abstraction
Value returning Functions
Java Programming Language
Class: Special Topics Overloading (methods) Copy Constructors
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Presentation transcript:

CSC 270 – Survey of Programming Languages C++ Lecture 3 - Introducing Objects

Object-Oriented Programming Object-oriented programming (or OOP) attempts to allow the programmer to use data objects in ways that represent how they are viewed in the real world with less attention to the implementation method. An object is characterized by its name, its properties (values that it contains) and its methods (procedures and operations performed on it).

Principles of OOP There are four main principles of OOP: Data Abstraction - our main concern is what data represents and not how it is implemented. Encapsulation - Private information about an object ought not be available the outside world and used only in prespecified ways. Polymorphism - There may be more than version of a given function, where the different functions share a name but have different parameter lists Inheritance - New classes of objects can be built from other classes of objects.

Defining A Class of Objects Defining a class of objects is similar to defining a type of structure, except that we can add functions as well as variables. By default, any item include is private (available only to functions within the class of objects) unless we include the keyword public.

Syntax For a Class Definition The syntax is: class classname { public: declarations for public functions and variables private: declarations for private functions and variables };

Example of a Class definition class point { public: void read(void); void write(void); float distance(void); float distance(point p); private: float x, y; };

Writing a Class Function float point::distance(void) { float a; a = sqrt(x * x + y * y); return(a); } class name goes here assumed to be the class properties

Example: Rewriting the Original Age Program Let’s rewrite the program that asked for name and age and then printed these items. There are two data items, both of which should be private: name and age. There are two procedures, both of which should be public: read and write.

age10.cpp #include using namespace std; const int namelen = 12; class oldguy { char name[namelen]; int age; public: void read(void) { cout << "What\'s your name\t?"; cin >> name; cout << "How old are you\t?"; cin >> age; }

void write(void) { cout << name << " is " << age << " years old." << endl; } }; int main(void) { oldguy me; me.read(); me.write(); return (0); }

Putting public Before private It is better to place the public members of the class before the private member because these are the ones that we want programmers to think in term of. To ensure this, we place the keyword public at the top followed by the public members. Below the public members, we place the word private followed by the private members. We can write the body of the member function inside the declaration (if it’s short) or outside (where we must write ClassName:: to indicate membership).

age11.cpp #include using namespace std; const int namelen = 12; class oldguy { public: void read(void); void write(void); private: char name[namelen]; int age; };

void oldguy::read(void) { cout << "What\'s your name\t?"; cin >> name; cout << "How old are you\t?"; cin >> age; } void oldguy::write(void) { cout << name << " is " << age << " years old." << endl; }

int main(void) { oldguy me; me.read(); me.write(); return(0); }

Member Functions and Parameters Functions belonging to a class can have parameters, including other objects of the same class or different class. If you pass as a parameter an object of the same class, you must use the name of the object when specifying its members. E.g., y is an item in this object, q.y is an item in object q.

age12.cpp #include using namespace std; const int namelen = 12; // A class of object which contains name and age class oldguy { public: void read(void); void write(void); bool older(oldguy him); bool younger(oldguy him); private: char name[namelen]; int age; };

// read() - Reads in name and age void oldguy::read(void) { cout << "What\'s your name\t?"; cin >> name; cout << "How old are you\t?"; cin >> age; } // write() - Writes name and age void oldguy::write(void) { cout << name << " is " << age << " years old." << endl; }

//older() - Returns true if this guy is older // Returns false if this guy is younger // or the same age bool oldguy::older(oldguy him) { return(age > him.age); } //younger() - Returns true if this guy is // younger // Returns false if this guy is // older or the same age bool oldguy::younger(oldguy him) { return(age < him.age); }

int main(void) { oldguy me, him; me.read(); him.read(); if (me.older(him)) cout << "I\'m older." << endl; else if (me.younger(him)) cout << "I\'m younger." << endl; return(0); }

Example: Complex Numbers Complex numbers are number of the type w = x + iy where x and y are real and i is the square root of -1. We can define the operations addition, subtraction and multiplication.

Complex Number Operations If our two complex numbers are u and v: – If w = u + v Re w = Re u + Re v Im W = Im u + Im v – If w = u - v Re w = Re u - Re v Im W = Im u - Im v – If w = u · v Re w = Re u · Re v - Im u · Im v Im w = Re u · Im v - Im u · Re v

complx1.cpp #include using namespace std; class complex { public: void read(void); void write(void); complex add(complex v); complex sub(complex v); complex mult(complex v); private: float real; float imag; };

// read() - Read in a Complex value void complex::read(void) { cout << "Real\t?"; cin >> real; cout << "Imaginary\t?"; cin >> imag; } // write() - Write a complex value void complex::write(void) { cout << '(' << real << ", " << imag << ')'; }

// add() - Returns the sum of this value + v complex complex::add(complex v) { complex w; w.real = real + v.real; w.imag = imag + v.imag; return(w); } // sub() - Returns the difference of // this value - v complex complex::sub(complex v) { complex w; w.real = real - v.real; w.imag = imag - v.imag; return(w); }

// Mult() - Returns the product of // this value times v complex complex::mult(complex v) { complex w; w.real = real * v.real - imag * v.imag; w.imag = real * v.imag - imag * v.real; return(w); }

// ComplexDemo() - Demonstrate the complex class int main(void) { complex u, v, w; u.read(); v.read(); w = u.add(v); w.write(); w = u.sub(v); w.write(); w = u.mult(v); w.write(); return(0); }

Constructors Sometimes we need an object to have some initial values set when we define it. This can be done implicitly by writing a constructor. Constructors are called automatically when the program enters the function where the object is declared. Constructors share a name with the class and have no result type, not even void.

Default Constructors If an object is declared without any parameters, the default constructor is called. A default constructor has no parameters.

Conversion Constructors Thus, a conversion constructor initializes some or all of the values within the object. To use a conversion constructor, an object must be declared including (in parentheses) the initial values: MyClass MyObject(2, "name");

complx2.cpp #include using namespace std; class complex { public: complex(void); complex(float a, float b); complex(int a, int b); void read(void); void write(void); complex add(complex v); complex sub(complex v); complex mult(complex v);

private: float real; float imag; }; // complex() - A Default Constructor complex::complex(void) { real = imag = 0.0; } // complex() - A Conversion Constructor complex::complex(float a, float b) { real = a; imag = b; }

// complex() - A Conversion Constructor complex::complex(int a, int b) { real = (float) a; imag = (float) b; } // read() - Read in a Complex value void complex::read(void) { cout << "Real\t?"; cin >> real; cout << "Imaginary\t?"; cin >> imag; }

// write() - Write a complex value void complex::write(void) { cout << '(' << real << ", " << imag << ')'; } // add() - Returns the sum of this value + v complex complex::add(complex v) { complex w; w.real = real + v.real; w.imag = imag + v.imag; return(w); }

// sub() - Returns the difference of // this value - v complex complex::sub(complex v) { complex w; w.real = real - v.real; w.imag = imag - v.imag; return(w); }

// mult() - Returns the product of // this value times v complex complex::mult(complex v) { complex w; w.real = real * v.real - imag * v.imag; w.imag = real * v.imag - imag * v.real; return(w); }

//ComplexDemo() - Demonstrate the complex class int main(void) { complex u(1, 1), v, w; v.read(); w = u.add(v); w.write(); w = u.sub(v); w.write(); w = u.mult(v); w.write(); return(0); }

Rewriting average.cpp Let’s rewrite average so that it is an object with the private data items (first and last name and four exam grades in an array) and three functions ( read, write and findaverage ). By writing two versions of write (one with the average, one without), we overload the function. It will choose the one matching the parameter list.

avggrade.cpp #include using namespace std; const int namelen = 15, numexams = 4; class student { public: void read(void); void write(void); void write(float average); float findaverage(void); private: char firstname[namelen], lastname[namelen]; int exam[numexams]; };

// read() - Read the input about the student void student::read(void) { int i; cout << "First name\t?"; cin >> firstname; cout << "Last name\t?"; cin >> lastname; for (i = 0; i < numexams; i++) { cout << "Enter grade for exam #" << i+1 << "\t?"; cin >> exam[i]; }

// FindAverage() - Returns the average of n // exam scores float student::findaverage(void) { int i, sum = 0; for (i = 0; i < numexams; i++) sum += exam[i]; return((float) sum/numexams); }

// WriteStudent() - Print the data about the // student without the // average void student::write(void) { int i; cout << firstname << ' ' << lastname << " scored : " << endl; for (i = 0; i < numexams; i++) cout << exam[i] << endl; }

// WriteStudent() - Print the data about the // student including the // average void student::write(float average) { int i; cout << firstname << ' ' << lastname << " scored : " << endl; for (i = 0; i < numexams; i++) cout << exam[i] << '\t'; cout << "\n\twhich resulted in an average of " << average << endl; }

// AvgGrade() - Averages the grades on n exams int main(void) { student s; float average; // Read the students name and test scores s.read(); // Find the average average = s.findaverage(); // Print the results s.write(average); return(0); }