#include <iostream> #include <cstdlib>

Similar documents
CE221 Programming in C++ Part 1 Introduction

Implementing an ADT with a Class

Chapter 11 Object and Object- Relational Databases

Fast Introduction to Object Oriented Programming and C++

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

QUIZ. What is wrong with this code that uses default arguments?

G52CPP C++ Programming Lecture 9

C++ (Non for C Programmer) (BT307) 40 Hours

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Introduction to Classes

An Introduction to C++

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Introduction to C++ Systems Programming

Lecture 7. Log into Linux New documents posted to course webpage

And Even More and More C++ Fundamentals of Computer Science

G52CPP C++ Programming Lecture 13

Chapter 17: Linked Lists

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Cpt S 122 Data Structures. Introduction to C++ Part II

EL2310 Scientific Programming

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Partha Sarathi Mandal

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

C++ Important Questions with Answers

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Instantiation of Template class

September 10,

Abstract Data Types and Encapsulation Concepts

4.1 Introduction Programming preliminaries Constructors Destructors An example... 3

Tuesday, 22 September 2009

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Object-Oriented Principles and Practice / C++

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Object Oriented Design

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Interview Questions of C++

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Computer Science 306 Study Guide

ADTs & Classes. An introduction

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Extending Classes (contd.) (Chapter 15) Questions:

EL2310 Scientific Programming

Chapter 10 Introduction to Classes

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Abstraction in Software Development

Classes and Objects. Class scope: - private members are only accessible by the class methods.

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

BCS Higher Education Qualifications. Diploma in IT. Object Oriented Programming Syllabus

Lecture 18 Tao Wang 1

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Data Structures using OOP C++ Lecture 3

Chapter 11. Abstract Data Types and Encapsulation Concepts

Object-Oriented Programming in C++

Object Oriented Software Design II

Special Member Functions

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

CPS 506 Comparative Programming Languages. Programming Language

Exercise. Game Programming in C++ Overview. Art vs. Science in Programming. Organising your code. Organising your code

Lecture 02, Fall 2018 Friday September 7

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Data Structures (list, dictionary, tuples, sets, strings)

Tokens, Expressions and Control Structures

Data Abstraction. Hwansoo Han

Object-Oriented Programming

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CS201 Some Important Definitions

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Chapter 6 Introduction to Defining Classes

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

CS250 Final Review Questions

More C++ : Vectors, Classes, Inheritance, Templates

Encapsulation in C++

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Introduction Of Classes ( OOPS )

CSE 303: Concepts and Tools for Software Development

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Software Design and Analysis for Engineers

Introduction to C++ Introduction to C++ 1

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

COMP6771 Advanced C++ Programming

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Lecture 10: building large projects, beginning C++, C++ and structs

CS304 Object Oriented Programming Final Term

CS3157: Advanced Programming. Outline

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Absolute C++ Walter Savitch

Object-Oriented Design (OOD) and C++

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

What are the characteristics of Object Oriented programming language?

Transcription:

Classes and Objects

Classes The structure data type can be used in both C and C++ Usually a structure is used to store just data, however it can also be used to store functions that can work on the data. In C++ we store the data and the operation that can be performed on that data together in the same entity. This entity is know as a class

#include <iostream> #include <cstdlib> typedef struct Point { float x; float y; float z; Point(float _x, float _y, float _z){ x=_x; y=_y; z=_z; } void print(){ std::cout<<"["<<x<<","<<y<<","<<z<<"]\n"; } }Point_t; int main() { Point p(2,3,4); p.print(); return EXIT_SUCCESS; }

The Anatomy of a class A Class has two parts (just like an ADT) a private (hidden) part a public interface The public part defines the behaviour of the object (methods) The private part contains the data (attributes) It is normal practice to put attributes in the private part of the class where they can only be accessed by methods

Special Class Methods Methods are functions which operate upon the data in the class There are two special methods which allow us to create and destroy any data in the object Constructor (used to set the default attribute values of the object) Destructor (used to clear any memory allocated in the constructor)

Class Access Scope Classes allow different levels of access to various elements of the class Unlike structure where every element is visible. There are 3 areas of access public : visible to all private : hidden and only accessible to the class itself protected : only visible to descendants of the main class (used in Inheritance we shall see this later in the year)

mutable vs immutable A mutable object is one where the data may be modified after creation. An immutable object once created may not be modified We can further add to this distinction by mixing elements of both in a class Methods may also be tagged to say if they modify the internal state of the class or not. This is a form of C++ etiquette know as const correctness whilst not mandated by the language it should be considered as part of the design of our classes and methods. Adding const correctness at a later date is usually very painful

Unified Modelling Language (UML) Unified Modelling Language (UML) is a standardised general-purpose modelling language UML has a number of graphical element which allows us to describe various components of a software system in a standardised way We shall use the UML notation for class diagram when designing our classes as well as other elements from the UML 2.x standard

Basic Class Diagrams Superclass 1 to Many relationship A Class hierarchy Class 1 * Class Subclass using inheritance 0 or 1 to Many relationship Superclass Class 0..1 * Class Subclass Subclass Subclass

A more detailed class Class Name A unique name for out class Attribute Attribute Operation Operation A number of attributes A list of methods

Specifying Attributes Colour - m_r : float - m_g : float Symbol Visibility - m_b : float + public - m_a : float # protected attributes are specified in the following way - private [visibility] name : [data type] data type is any class type or built in data type

Specifying Methods Colour - m_r : float - m_g : float - m_b : float - m_a : float + Red() : float + Red(_r : float) + Green() : float + Green(_g : float) + Blue() : float + Blue(_b : float) + Alpha() : float + Alpha(_a : float) Symbol Visibility + public # protected - private Methods are defined as follows [visibility] Name( [param] ) : [return type] param := [name] : [data type] can have param,param...

Accessors and Mutators In the previous example we had the methods opposite These methods are know as Accessors (or Get methods) the one returning the value And Mutators ( or Set Methods ) which is used to set the class attribute value You will notice the get method has a const at the end of the definition as it doesn t mutate the class 1 /// @brief accessor method to get the red attribute 2 /// @returns m_r the red colour intensity value 3 4 inline float Red() 5 { 6 return m_r; 7 } const 8 /// @brief mutator method to set the red colour intensity value 9 /// @param [in] _r the red value to set 10 11 inline void Red( 12 float _r 13 ) 14 { 15 m_r = _r; 16 }

Accessors (Priess 1998) An accessor is a method that accesses (returns) an attribute of an object but doesn t modify the object In the simplest case, an accessor just returns the value of one of the attributes. In general, an accessor performs some computation using the attributes as long as that computation does not modify any of the attributes.

Mutators (Priess 1998) A mutator is a method that can modify an object. In the simplest case, a mutator just assigns a new value to one of the attributes. In general, a mutator performs some computation and modifies any number of attributes.

Classes It is standard practice to split the class into two separate files. A.h Header file is used to define the class and prototype the methods and data for this class. A.cpp file is used to contain the actual class code and algorithmic elements. To link these two elements together we need to tell the compiler which class the methods in the.cpp file belong to.

C++ Scope Resolution Operator :: The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. This is how C++ allows us to have different classes with the same member function names (polymorphism) We use the :: to imply membership to a particular class and differentiate the different methods / class relationships

1 #ifndef COLOUR_H 2 #define COLOUR_H 3 4 class Colour 5 { 6 public : 7 8 9 ///\brief default constructor set all values to 0 except alpha 10 inline Colour() : 11 m_r(0.0f), 12 m_g(0.0f), 13 m_b(0.0f), 14 m_a(1.0f){;} 15 16 /// \brief constructor passing in r g b components 17 /// @param[in] _r red component 18 /// @param[in] _g green component 19 /// @param[in] _b blue component 20 /// @param[in] _a the alpha component 21 22 inline Colour( 23 const Real _r, 24 const Real _g, 25 const Real _b, 26 const Real _a 27 ) : 28 m_r(_r), 29 m_g(_g), 30 m_b(_b), 31 m_a(_a){;} 32 33 private : 34 /// @brief the red colour component 35 float m_r; 36 /// @brief the green colour component 37 float m_g; 38 /// @brief the blue colour component 39 float m_b; 40 /// @brief the alpha colour component 41 float m_a; 42 43 }; 44 45 #endif C++ class syntax we use the class keyword to define a class class [name] { }; { }; scope defines members of the class public : defines publicly visible area private : defines hidden area classes are usually defined in a.h file

inline methods In the previous example the inline pre-fix is used to tell the compiler that the Colour constructor methods are part of the header file This is actually pertinent to older compilers however modern compilers will tend to do their own thing. Usually we only use this when we want to define the code in the header. This may also be a factor when defining templates.

inline methods Let the compiler do the work (it can optimise better than us) At -O2 optimisation level the inlining is done when the compiler thinks it is worth doing (a heuristic is used) and if it will not increase the size of the code. At -O3 it is done whenever the compiler thinks it is worth doing, regardless of whether it will increase the size of the code. Additionally, at all levels of optimisation (enabled optimisation that is), static functions that are called only once are inlined.

Single File Inclusion header files define interfaces for functions, structures, unions and classes They may also define variables, however if this header file is then included in more than one module the linker will complain as the same variable is defined twice. To overcome this problem we can use Single File Inclusion The traditional way of doing this is as follows Use the name of the Header file as an identifier for the pre-processor and create a unique #define name place a #include directive in the code to define the module name If the #define does not exist then it will be included if it does there is no need to include it again.

Colour.h 1 #ifndef COLOUR_H 2 #define COLOUR_H 3 #include Colour.h File1.cpp 4 class Colour 5 { COLOUR_H not defined 6 public : 7 8... So we define it and the rest of the code to the #endif 9 10 }; 11 12 #endif #include Colour.h File2.cpp COLOUR_H is defined so skip to the #endif

Constructors (ctor) When an object is created there are certain processes which must take place Instantiation always involves the allocation of memory for the objects state data. The methods do not require and memory as these are consistent for all objects of the class and are handled in the class itself. The special method which allocates the memory for an object is know as the 'constructor' There are three basic types of constructor The default constructor User defined Constructor The Copy Constructor

The default constructor The default constructor takes no parameters and has no return type It performs no processing on the object data just memory allocation It will always be called by the compiler if no user defined constructor is provided The default constructor is not referred to by the programmer in the class definition

User Defined Constructors These constructors may be used to pass parameter values to the object These may be used to set default object values It is possible to have more than one constructor in a class passing different parameters This is known as overloading and gives more flexibility to the way the object can be instantiated

Colour - m_r : float - m_g : float - m_b : float - m_a : float + Colour() + Colour(_r : float, _g : float, _b : float, _a : float) + Red() : float + Red(_r : float) + Green() : float + Green(_g : float) + Blue() : float + Blue(_b : float) + Alpha() : float + Alpha(_a : float) User defined default constructor User defined parameterised constructor

default ctor 1 /// @brief default constructor set all values 2 /// to 0 except alpha which is set to 1 3 inline Colour() : 4 m_r(0.0f), 5 m_g(0.0f), set each of the attributes to a default value by calling it s own ctor* 6 m_b(0.0f), 7 m_a(1.0f){;} no other code * yes float has a constructor as do all C++ data types 1 int a = int(2); 2 float b = float(4.5);

user defined ctor 1 /// @brief constructor passing in r g b a components 2 /// @param[in] _r red component 3 /// @param[in] _g green component 4 /// @param[in] _b blue component 5 /// @param[in] _a the alpha component 6 7 inline Colour( 8 const Real _r, 9 const Real _g, 10 const Real _b, 11 const Real _a 12 ) : 13 m_r(_r), 14 m_g(_g), 15 m_b(_b), 16 m_a(_a){;} here we are passing in individual values to set the class attributes with

The copy ctor The copy constructor creates a new class as a copy of an existing class As the classes are of the same type they both know about each others internal state (private attributes) To stop mutation of the class being copied we must make it read only To do this we use the const prefix on the ctor parameter being passed in.

Copy ctor 1 /// @brief constructor passing in a Colour 2 /// @param[in] _c the colour to use 3 4 inline Colour( 5 const Colour &_c 6 ) : 7 m_r(_c.m_r), 8 m_g(_c.m_g), 9 m_b(_c.m_b), 10 m_a(_c.m_a){;} use const to make the class passed in read only use. to access the class attributes m_r(_c.m_r) is basically saying set the current class member m_r to the value of the parameter passed in _c.m_r

References are Aliases not Pointers A reference is another name for an existing object. They are not pointers! There are no null references all references require initialisation ref1.cpp:8:7: error: declaration of reference variable 'x' requires an initializer int &x; ^ 1 error generated.

& and C++ In C++ the & is an explicit reference This means that the object passed using the & prefix is effectively a pointer but we are not using the * prefix as used in C In C++ *_a indicates that the value is a pointer and we may modify it in a function In C++ &_a is a reference (means we don t copy the value) but still behaves like a pointer const &_a means that it is a constant reference to a value. This means it is copied like a pointer but is read only.

References are Aliases not Pointers A reference is an alias for an object that already exists prior to the initialisation of the reference Once a reference is initialised to refer to a particular object, it cannot later be made to refer to a different object; a reference is bound to the initialiser. But why bother?

1 #include <stdio.h> 2 #include <stdlib.h> 3 4 /// @brief a function to swap two values 5 /// will make i<=>j 6 /// @param[in,out] *io_i the first value 7 /// @param[in,out] *io_j the 2nd value 8 9 void swapnum( 10 int *io_i, 11 int *io_j 12 ) 13 { 14 int temp = *io_i; 15 *io_i = *io_j; 16 *io_j = temp; 17 } 18 19 int main() 20 { 21 int a = 10; 22 int b = 20; 23 printf("a is %d and B is %d\n", a, b); 24 25 swapnum(&a, &b); 26 printf("a is %d and B is %d\n", a, b); 27 return EXIT_SUCCESS; 28 } C example Pass Pointers to values Swap memory addresses notice we pass the memory address via & here 1 A is 10 and B is 20 2 A is 20 and B is 10

1 #include <iostream> 2 #include <cstdlib> 3 4 /// @brief a function to swap two values 5 /// will make i<=>j 6 /// @param[in,out] &io_i the first value 7 /// @param[in,out] &io_j the 2nd value 8 9 void swapnum( 10 int &io_i, 11 int &io_j 12 ) 13 { 14 int temp = io_i; 15 io_i = io_j; 16 io_j = temp; 17 } 18 19 int main() 20 { 21 int a = 10; 22 int b = 20; 23 std::cout<< "A is "<<a<<" and B is "<< b<<std::endl; 24 25 swapnum(a, b); 26 std::cout<< "A is "<<a<<" and B is "<< b<<std::endl; 27 28 return EXIT_SUCCESS; 29 } C++ example Pass parameters by reference notice now we don t have the confusing * s everywhere we now just pass the variables 1 A is 10 and B is 20 2 A is 20 and B is 10

Did you spot the error?

The Orthodox Canonical class form ( rule of 3) As a general rule (and rules are made to be broken) all classes should define four important functions A default constructor :- This is used internally to initialise objects and data members when no other value is avaliable A copy constructor :- This is used, among other places, in the implementation of call-by-value parameters An assignment operator. This is used to assign one value to another. A destructor. This is invoked when an object is deleted. (more of this soon)

Rule of 5 C++ 11 gives some new methods of object creation an ownership and gives us a new rule destructor copy constructor move constructor copy assignment operator move assignment operator More next year.

Next Time We will look at how we can actually control objects This will involve managing the lifetimes of multiple objects and getting objects to manage their internal states. We will also see how we can pass messages to objects and get them to respond.

References Budd, T 2002 An introduction to Object Oriented programming 3rd Edition. Addison Wesley Parsons, David. Object Oriented Programming with C++ Thomson Learning; 2nd edition 8 Nov 2000 Priess B. Data Structures and Algorithms with Object-Oriented Design Patterns in C++ Wiley 1998 Eckel B. Thinking in C++, 2nd ed. Volume 1 Prentice Hall 2000 Dewhurst S. C++ Common Knowledge Pearson Education 2011

Further Reading http://en.wikipedia.org/wiki/mutable_object http://www.parashift.com/c++-faq-lite/const-correctness.html http://en.wikipedia.org/wiki/unified_modeling_language http://en.wikipedia.org/wiki/class_diagram http://www.ibm.com/developerworks/rational/library/content/ RationalEdge/sep04/bell/ http://www.parashift.com/c++-faq-lite/inline-functions.html