Object-Oriented Programming in C++ More examples of Association.

Slides:



Advertisements
Similar presentations
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
Object-Oriented Programming in C++ Lecture 7 Polymorphism.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
Inheritance and Polymorphism CS351 – Programming Paradigms.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data;
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Inheritance in Classes tMyn1 Inheritance in Classes We have used the Box class to describe a rectangular box – our definition of a Box object consisted.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Object-Oriented Programming in C++
Structured Programming Instructor: Prof. K. T. Tsang Lecture 13:Object 物件 Oriented 面向 Programming (OOP)
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
C++ Memory Overview 4 major memory segments Key differences from Java
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Overview of C++ Polymorphism
11 Introduction to Object Oriented Programming (Continued) Cats.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
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.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
CS1201: Programming Language 2 Classes and objects Inheritance Nouf Aljaffan Edited by : Nouf Almunyif.
A First Book of C++ Chapter 12 Extending Your Classes.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Chapter 2 Objects and Classes
Polymorphism &Virtual Functions
Inheritance & Polymorphism
Chapter 5 Classes.
Object Lifetime and Dynamic Objects
Polymorphism & Virtual Functions
group work #hifiTeam
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
Overview of C++ Polymorphism
CS410 – Software Engineering Lecture #5: C++ Basics III
SPL – PS4 C++ Advanced OOP.
Presentation transcript:

Object-Oriented Programming in C++ More examples of Association

Relationships between classes Consider “A flat is a type of residential property” “A flat has a kitchen” What can we say about these two statements? – Identify the nouns Flat Residential Property Kitchen

Concept of Containment “A flat is a type of residential property” – “is a” implies inheritance “A flat has a kitchen” – “has a” implies that one class contains another Called Containment – Flat can contain an instance of kitchen – Or can contain a pointer to a kitchen

Containment Flat -theKitchen: Kitchen Kitchen -numSockets: int Flat -pKitchen: Kitchen * Kitchen -numSockets: int

Class to be contained class Kitchen { private: int numSockets; public: Kitchen() {numSockets=0;} void setNumSockets(int); int getNumSockets(); }; Kitchen.cpp #include "Kitchen.h" void Kitchen::setNumSockets(int nSockets) { numSockets = nSockets; } int Kitchen::getNumSockets() { return numSockets; } Kitchen.h

Class containing an instance Flat.h #include "Kitchen.h" class Flat { private: Kitchen theKitchen; public: Flat() {} int getKitchenSockets() { return theKitchen.getNumSockets();} };

Containing an Instance app.cpp #include #include "Flat.h" using namespace std; int main(void) { Flat f; cout << “Flat has " << f.getKitchenSockets() << " sockets." << endl; return 0; } Output: My flat has 0 sockets.

Construction and Destruction A Flat contains a Kitchen instance the Kitchen constructor is called when the Flat is constructed when the Flat goes out of scope, its destructor is called automatically this will cause the Kitchen to go out of scope – so its destructor will be called

Constructing the Kitchen notice that we will always construct a kitchen with 0 sockets the default constructor for Kitchen is called when the flat is constructed it would be better to specify the number of sockets in the constructor of both Kitchen and Flat

Constructing a kitchen with variable sockets add another Kitchen constructor Kitchen(int nSocks) : numSockets(nSocks) {} and another Flat constructor Flat(int nKitchenSockets) : theKitchen(nKitchenSockets) {} in main, construct a luxury kitchen Flat f(3); cout << "Flat has " << f.getKitchenSockets() << " sockets." << endl; output: Flat has 3 sockets.

Containing a Pointer Flat.h #include "Kitchen.h" class Flat { private: Kitchen *pKitchen; public: Flat(int nKitchenSockets):pKitchen(new Kitchen(nKitchenSockets)) {} ~Flat() {delete pKitchen;} int getKitchenSockets() { return pKitchen->getNumSockets(); } };

Containing a pointer no change in app.cpp int main(void) { Flat f(3); cout << "Flat has " << f.getKitchenSockets() << " sockets." << endl; return 0; } Output: Flat has 3 sockets.

Construction and Destruction here we construct a new Kitchen object when we construct a new Flat we need to provide a destructor to delete the Kitchen when the Flat is deleted here the containment relationship is clear – the Kitchen cannot exist if the Flat is destroyed

Alternative we could pass the Flat constructor a pointer to a Kitchen object that has been constructed previously Flat(Kitchen *k) : pKitchen(k) {} in main: Kitchen * k = new Kitchen(2); Flat f(k); we need to think about the destructor – should it delete the Kitchen object? – or will there be other objects outside the flat that still refer to it? not likely in this case but what if the case where a Person has an Address? – a Module has a Teacher?

Difference between Instance and Pointer A pointer is essential if we want to change which object we point to during the lifetime of the container object – ie change the Award taken by a Student Using a pointer, the contained object – can be passed as an argument to the Constructor of the container, – or set via a member method of the container class Using polymorphism, the contained object could be a subtype of the member type – the Student could be on a BSc or MSc award

Difference between Instance and Pointer Using a pointer, the container class can contain a member attribute that is a pointer to an instance of the same class as the container object Person class could have a "mother" attribute this could be a pointer to another Person object not possible with an instance member can't define a member of class Person before the class Person has been defined

Person containing a Person class Person { private: Person mother; string name; public: Person(string n):name(n) { } Person getMother() {return mother;}; void setMother(Person m) { mother = m; } }; not allowed: error C2460: 'Person::mother' : uses 'Person', which is being defined

Person containing a Person pointer class Person { private: Person * mother; string name; public: Person(string n):name(n) { } Person * getMother() {return mother;}; void setMother(Person * m) { mother = m; } }; OK – mother is a pointer, which is the same size no matter what is being pointed to

Circular dependencies What if class A contains a member of type class B and class B contains a member of type class A? Circular Dependencies are very difficult in C++ Class B needs to be defined before it is used in Class A, but Class B needs Class A to be defined first Compiler will complain solution is to use a forward class declaration – similar to using a method prototype

Forward declaration in A.h: class B; // forward declaration class A { public: B* b; }; in B.h: class A; // forward declaration class B { public: A* a; };

Virtual Destructors in an inheritance hierarchy it is important to declare the base class destructor virtual if any of the derived classes contain pointers then the correct destructor will be called when a polymorphic container object is deleted – which should delete the objects pointed to destructors run in the opposite order to constructors – bottom up – derived class to base class

One-to-many association a Person could have many Accounts – might have different subtypes a Vehicle could have one or more Engines – Airplane one-to-many association is implemented using an array or container class – we will discuss C++ containers next lecture good for polymorphism – declare the array or container to hold the base type – fill it with objects of different subtypes

A Person with many vehicles class Person { private: vector theVehicles; public: Person(){} virtual ~Person() {} void addVehicle(Vehicle * v) { theVehicles.push_back(v); } void moveVehicles() { for (int i=0; i < theVehicles.size(); i++) { theVehicles[i]->move(); } };

Using Person #include "Vehicle.h" #include "Person.h" #include using namespace std; int main(){ Person p; p.addVehicle(new Vehicle("Transporter 54")); p.addVehicle(new Airplane("Tornado 2431", 14)); p.addVehicle(new Car("Ford Anglia 22")); p.moveVehicles(); }

Comparison to Java in Java, all member variables are contained by reference (pointer) unless they are primitive types – int, boolean, char, double we construct them with the keyword new – either in the constructor body – or elsewhere, and assign them to the attributes reference counting is taken care of the garbage collector which runs periodically and deletes all objects with no references

Summary In this lecture we have: discussed association compared – containment by instance – containment by pointer looked at destructors in more detail considered circular dependencies looked at one-to-many association