Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1



Similar documents
13 Classes & Objects with Constructors/Destructors

Comp151. Definitions & Declarations

C++FA 5.1 PRACTICE MID-TERM EXAM

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

C++ Overloading, Constructors, Assignment operator

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Computer Programming C++ Classes and Objects 15 th Lecture

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Object Oriented Software Design II

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

C++ INTERVIEW QUESTIONS

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

CISC 181 Project 3 Designing Classes for Bank Accounts

Chapter 5 Functions. Introducing Functions

Compile-time type versus run-time type. Consider the parameter to this function:

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

EP241 Computer Programming

Object Oriented Software Design II

Ch 7-1. Object-Oriented Programming and Classes

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Advanced Data Structures

C++ Crash Kurs. C++ Object-Oriented Programming

Friendship and Encapsulation in C++

Constructor, Destructor, Accessibility and Virtual Functions

Sources: On the Web: Slides will be available on:

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

Brent A. Perdue. July 15, 2009

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Object Oriented Software Design II

An Incomplete C++ Primer. University of Wyoming MA 5310

OpenCL Static C++ Kernel Language Extension

Glossary of Object Oriented Terms

Appendix K Introduction to Microsoft Visual C++ 6.0

C++ Programming Language

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Introduction to Programming Block Tutorial C/C++

explicit class and default definitions revision of SC22/WG21/N1582 = and SC22/WG21/ N

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Formatting Numbers with C++ Output Streams

Course notes Standard C++ programming

1. Polymorphism in C++...2

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Basics of C++ and object orientation in OpenFOAM

Conditions & Boolean Expressions

Compiler Construction

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

The C Programming Language course syllabus associate level

CSI33 Data Structures

Basic Object-Oriented Programming in Java

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

El Dorado Union High School District Educational Services

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Moving from CS 61A Scheme to CS 61B Java

Chapter One Introduction to Programming

Data Structures using OOP C++ Lecture 1

Note: Syntactically, a ; is needed at the end of a struct definition.

VB.NET - CLASSES & OBJECTS

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Coding conventions and C++-style

Class 16: Function Parameters and Polymorphism

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

Curriculum Map. Discipline: Computer Science Course: C++

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Java CPD (I) Frans Coenen Department of Computer Science

CEC225 COURSE COMPACT

3 Representation in C++.

6. Control Structures

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

CIS 190: C/C++ Programming. Polymorphism

A deeper look at Inline functions

C++ Support for Abstract Data Types

Conversion Constructors

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

N3458: Simple Database Integration in C++11

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Function Overloading I

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Sequential Program Execution

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Chapter 13 Storage classes

Passing 1D arrays to functions.

Variable Base Interface

Transcription:

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g int and double. However, real programs have to deal with more complicated objects e.g complex numbers, dates and times, matrices, 4-vectors Typically these are composites of the basic types for which we want to define some set of rules e.g addition of complex numbers. We would like to be able to write something like: Complex a,b,c;...... c = a + b; where a,b,c represent complex numbers. Fortunately C++ allows one to do this :) Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 2

Introduction to Classes In C++ new user-defined data types can be declared by using classes. A class can be thought of as a collection of one or more variables together with their associated functions (methods). In order to define such a new data type one uses the class construct. (Usually in a header file) one would write a definition of the form: class Example { [private:] member_1 member_2;... [public:] member_3; member_4;... }; Here member_1...member_n is a declaration of a member variable (which may be of another class type) or a member function. The keywords private and public denote access (more about this later). Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 3

Introduction to Classes Let us consider as a concrete example a class to represent dates. Its declaration could look like class Date{ public: unsigned day; unsigned month; unsigned year; void Set(unsigned d, unsigned m, unsigned y); void Print(); }; This class has 3 (public) data members, each being an unsigned int and 2 (public) member functions. Such a class declaration is usually found in a.h file. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 4

Introduction to Classes Member Function Implementations The functions which are prototyped in a class declaration must be defined. As usual these are normally placed in a.cpp file. In order to distinguish a class member function from a normal function one uses the :: (scope resolution) syntax. e.g. for the Date class one would define: void Date::Set(unsigned d, unsigned m, unsigned y) { day =d; month=m; year =y; } void Date::Print() { cout<<"date is "<<day<< "-" <<month<< "-" << year << endl; } N.B. The class member variables ( day, month, year ) are used as normal variables within member functions. They are NOT declared within the member functions! Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 5

Introduction to Classes Using Class Objects A class declaration provides a new user-defined type. This is demonstrated in the example program date1.cpp Once we have this we can create objects of the particular class type. e.g. Date d; Declares d to be an object of type class Date. Notice the distinction between a class and an object. We say that an object is an instance of a class. The relationship is the same as that between a variable and a data type. Accessing the public members (functions and data) from outside the class scope requires the dot. operator. e.g. d.set( 24, 2, 1998); cout << "year is " << d.year << endl; d.print(); A second example of using a very simple class is the example rect1.cpp, which shows how one can use a class to represent rectangles. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 6

Public and Private members Public and Private Members The key words public and private denote access to the members. private variables my only be assigned to or read by member (or friend) functions. private member functions may only be called by other member functions. public members have no such restrictions. N.B. The default access is private The Data Hiding Paradigm One important principle of Object Oriented programming is the idea of Data Hiding. This can be achieved by always doing the following: Make all data members private Interact with an object only via a well defined set of (member) interface functions. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 7

Public and Private members By applying the data hiding paradigm one can re-write the Date class (see date2.cpp ) class Date{ unsigned day; unsigned month; unsigned year; public: void Set(unsigned d, unsigned m, unsigned y); void Print() const; unsigned Day() const { return day; } unsigned Month() const { return month; } unsigned Year() const { return year; } }; Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 8

Public and Private members Now that the data members are private we have to provide a set of accessor functions: (Day(), Month(), Year() ) which provide an interface to Date objects. Here we have used two new features: the keyword const after a function prototype declares that a member function does not modify any of the member data. The second new feature we have used is to in-line the accessor functions. This is where the function definition is placed in the class declaration. This is commonly used for trivial (one or two statements say) functions which can then be optimized by the compiler. A second example is rect2.cpp Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 9

Constructors and destructors Constructors and Destructors For the Date class we have used the member function Set to initialize the member data. More generally when one creates an object one always needs to ensure that it is in some well defined initial state. This task is so common that a special function, called a constructor is provided for every class to facilitate this. The constructor takes the same name as the class and is called whenever an object of a class is created. If one does not explicitly provide a constructor a default constructor is provided by the compiler which takes no arguments and does not initialize any member data. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 10

Constructors and destructors Replacing the Set function by a constructor the Date declaration becomes: class Date{ unsigned day; unsigned month; unsigned year; public: Date(unsigned d, unsigned m,unsigned y); void Print() const; unsigned Day() const { return day; } unsigned Month() const { return month; } unsigned Year() const { return year; } }; Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 11

Constructors and destructors and the definition of the constructor could be: Date::Date(unsigned d, unsigned m,unsigned y) { day =d; month=m; year =y; } Notice that the constructor has NO return type. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 12

Constructors and destructors Once a constructor has been declared object creation can only take place by providing the correct number of arguments. For example, to create Date objects we have to provide the 3 arguments e.g. Date d( 9, 3, 1999); This ensures Date objects can only be created with their 3 data members initialized. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 13

Constructors and destructors The initiation of member data is so common that the is also a special syntax. An in-line declaration of the Date constructor could be:... Date(unsigned d, unsigned m,unsigned y):day(d),month(m),year(y) {}... The initialisation of the member data takes place before the constructor body. It is possible, and is fairly common, to overload constructors. For example, one might provide a second version of the Date constructor which takes no arguments and initializes the member data to correspond to todays date. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 14

Constructors and destructors Destructors There is also a special function called a Destructor, which is called whenever an object is destroyed (e.g. goes out of scope). This member function takes the special name ~classname where classname is the name of the class. e.g. for the Date class one could have the in-line destructor:... ~Date(){}... Destructors take no arguments and have no return value. Again, a default version (which does nothing) is supplied by the compiler if one isn't explicitly declared. It is not possible to overload destructors. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 15

Constructors and destructors Copy constructor There is a third special function provided by the compiler called the Copy Constructor (see p462). This is an overloaded form of the constructor which is called whenever a copy of an object is needed. For example: Date a = b; It is also implicitly used whenever an object is passed by value as a function argument or as a return value (there is also a default copyassignment function). By default this makes a simple byte-wise copy of the member data. Which is usually fine unless an object contains pointers. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 16

Constructors and destructors An explicit definition of a copy constructor (which is not actually needed in this case) could be: Date::Date(const Date& rhs) { day =rhs.day; month=rhs.month; year =rhs.year; } This creates a new Date object, with its member data initialized to be the same as an existing object. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 17

Friend Functions Friend Functions Sometimes it is necessary to allow a non-member function to have access to some of the private members of a class. Rather than making the members public, or creating extra accessor functions one can declare a function to be a friend A typical friend function several class objects as arguments. For example, consider a function which takes two objects and constructs a new Rectangle with width and height equal to the larger of the two quantities for the two rectangles. Such a function might be defined: Rectangle Surround(const Rectangle& a, const Rectangle& b) { double w=a.width; double h=a.height; if( b.width > w ) w = b.width; if( b.height > h ) h = b.height; return Rectangle(w,h); } Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 18

Friend Functions Notice here, that a Rectangle is returned by value (using the copy constructor). This function clearly needs to access the private data members, so it needs to be declared to be a friend. This can be done by adding the declaration: friend Rectangle Surround(const Rectangle& a, const Rectangle& b); to the Rectangle class declaration. See rect4.cpp. Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 19

Introduction to Classes Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 20