unit 7: introduction to object-oriented programming - …€¦ ·  · 2015-01-23association...

45
Unit 7 Introduction Concepts OOP in C++ Syntax Inline functions Accessors Canonical form Constructors Assignment Copy constructors Destructors static this const friend I/O Relations Association Aggregation and composition Generalization Exercises Unit 7: Introduction to Object-Oriented Programming Programming 2 2014-2015

Upload: vuongbao

Post on 02-May-2018

230 views

Category:

Documents


5 download

TRANSCRIPT

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Unit 7: Introduction to Object-OrientedProgrammingProgramming 2

2014-2015

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Index

1 Introduction to Object-Oriented Programming

2 Core concepts

3 OOP in C++

4 Relations

5 Exercises

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Definition

The OOP is a programming paradigm using objectsand their interactions to design software.The whole application can be seen as a set of objectsand relations between them.Although C++ is an object oriented language, it alsoallows imperative (procedural) programming.Get ready to change your mind and your programmingfoundations as you know.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Classes and objects

We’ve already used classes and objects inProgramming 2.

int i; // Declare a variable i of type int

string s; // Declare an object s of class string

Classes (compound types) are similar to the simpletypes, but they allow to extend the functional qualities.A class is a model to create objects of that type.An object of a given class is called an instance of thatclass (s is an instance of string).

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Differences between simple types and classes

A structure (simple type) can be seen as a light classwhich only stores visible data.Basically, a class is similar to a structure, but addingfunctions (class = data + methods).Classes also allow to consider the data as visible(public) or hidden (private).A class contains data and a series of functions tohandle the data called member functions.Member functions can access to the public and privatedata of their class.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Syntax (1/2)

Structure example:

struct Date {int day;int month;int year;

};

Basic/coarse class equivalence:

class Date {public:

int day;int month;int year;

}; // Attention: The semicolon is mandatory

By default, all the class members are private unlesspublic will be explicitly indicated.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Syntax (2/2)

Elements can be directly accessed like in a structure:

Date d;d.day=12;

But in a class it is not convenient to directly access theelements. Methods can be used instead to modify thedata.In the previous example, d.day=100 would be allowed.This situation can be controlled using methods.

class Date {private: // Only accesible from the class methods

int day;int month;int year;

public:bool setDate(int d, int m, int a) { ... };

};

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Core concepts

Principles of the object-oriented programming design:AbstractionEncapsulationModularityInheritancePolymorphism

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Abstraction

Abstraction is a term to refer to the essential features ofan object and its behaviour.Each object can perform tasks, inform and change itsstate, and communicate with other objects in thesystem without revealing how these features areimplemented.The abstraction process allows to select the relevantfeatures in a set and identify common behaviours tocreate new classes.The abstraction process takes place in the designstage.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Encapsulation

Encapsulation means to group at the same abstractionlevel all the elements that may belong to the sameentity.The interface is the part of the object which is visible toother objects (public). It’s the set of methods (andsometimes data) that we can use to communicate withan object.Each object hides its implementation and shows itsinterface.Interface: What the object can do. Implementation:How does it make it.The encapsulation protects the object propertiesagainst modification. Only the internal methods of theobject can access to its state.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Modularity

Modularity is the property that allows to divide anapplication in smaller parts (called modules) asindependent as possible.These modules can be compiled separately, althoughthey are connected with other modules.Usually, each class is implemented in an independentmodule, but classes with very similar functionalqualities can share a module.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Inheritance (not in Programming 2)

A classification hierarchy can be build with relatedclasses. For instance, a car (subclass) is also avehicle (superclass).Objects inherit the properties and behaviour of allclasses they belong to.Inheritance facilitates the information organization indifferent abstraction levels.Derived objects can share (and extend) their behaviourwithout implementing it again.Multiple inheritance occurs when an object inheritesfrom more than one class.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Polymorphism (not in Programming 2)

Polymorphism is the property to indicate that the sameexpression can refer to different actions. For instance,the method move() can do different actions in a planeor in a car.Different behaviours related to different objects canshare the same name.The references and object collections can containobjects of different types.

Animal *a = new Dog;Animal *b = new Cat;Animal *c = new Seagull;

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Class example (1/2)

UML diagram:

+ Rect(ax : int, ay : int, bx : int, by : int)+ ~Rect()+ width() : int+ height() : int+ area() : int

- x1 : int- x2 : int- y1 : int- y2 : int

Rect

// Rect.h (class declaration)class Rect{

private:int x1, y1, x2, y2;

public:Rect(int ax, int ay, int bx,int by); // Constructor~Rect(); // Destructorint width();int height();int area();

};

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Class example (2/2)

// Rect.cc (methods body)Rect::Rect(int ax, int ay, int bx, int by) {

x1=ax;y1=ay;x2=bx;y2=by;

}

Rect::~Rect() { }

int Rect::width() { return (x2-x1); }int Rect::height() { return (y2-y1); }int Rect::area() { return width()*height(); }

// main.ccint main(){

Rect r(10,20,40,50);cout << r.area() << endl;

}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Inline declarations (1/2)

Short methods can also be implemented in the classdeclaration.

// Rect.h (class declaration)class Rect{

private:int x1, y1, x2, y2;

public:Rect(int ax, int ay, int bx,int by);~Rect() {}; // Inlineint width() { return (x2-x1); }; // Inlineint height() { return (y2-y1); }; // Inlineint area();

};

It’s more efficient because when the program iscompiled, the code generated for the inline functions isinserted in the place where the function is called,instead of doing it in another place and make the call.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Inline declarations (2/2)

Inline functions can also be implemented outside theclass declaration (in the .cc file).

inline int Rect::width(){

return (x2-x1);}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Accessors

Due to the encapsulation principle, it’s not convenient todirectly access the member attributes.Usually, they are defined as private and beingaccessed using set/get/is methods (called accessors).

+ getDay () : int+ getMonth () : int+ getYear() : int+ setDay (d : int) : void+ setMonth (m : int) : void+ setYear (a : int) : void+ isLeap () : bool

- day : int- month : int- year : int

Date

The set accessors allow to control the attribute valuescorrectness.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Canonical form

All the classes should implement at least these fourimportant methods:

ConstructorAssignment operator (Not in Programming 2)Copy constructorDestructor

C++ creates these operations by default when they areundefined.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Constructors (1/3)

Classes usually have at least one constructor and onedestructor method.The constructor is called automatically when a newobject of the class is created. The destructor is calledwhen the object scope ends.If a constructor is undefined, the compiler will createone without parameters and doing nothing. Themember attributes of these objects will be uninitialized.There can be several constructors on a class withdifferent parameters (the constructors can beoverloaded). Overloading is a kind of polymorphism.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Constructors (2/3)

Constructor examples:

Date::Date() {day=1;month=1;year=1900;

}Date::Date(int d, int m, int y) {

day=d;month=m;year=y;

}

Constructor calls:

Date d;Date d(10,2,2010);

Date d(); // WRONG (frequent error)

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Constructors (3/3)

It’s better to use initialization than assignment, as it’smore efficient and predictable to initialize objects whenthey are created.

Date::Date(int d,int m,int y) : day(d), month(m), year(y){ }

Constructors with default parameters (only in headerfile .h)

Fecha(int d=1,int m=1,int a=1900);

A new object can be created in different ways with thisconstructor:

Date d;Date d(10,2,2010);Date d(10); // day=10

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Assignment operator

Two objects can be directly assigned (without usingcopy constructors).

Date d1(10,2,2011);Date d2;d2=d1; // Direct copy of the values of member attributes

The operator = can be redefined for our classes ifnecessary (Not in Programming 2).

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Copy constructors (1/2)

Similarly to assignment, a copy constructor creates anew object from an existing object.

// DeclarationDate (const Date &d);

// ImplementationDate::Date(const Date &d) :

day(d.day), month(d.month), year(d.year) {}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Copy constructors (2/2)

The copy constructor is automatically called when...A function returns an objectAn object is initialized when it’s declared

Date d2(d1);Date d2=d1;d1=d2; // Here the constructor is NOT called, but =

An object is passed by value to a function

void function(Date d1);function(d1);

If the copy constructor isn’t supplied, the compilercreates one with the same behaviour than operator =

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Destructors (1/2)

All the classes need a destructor (if it’s not supplied, thecompiler creates one by default).A destructor must free all the resources used by theobject (usually, dynamic memory).It’s a member function with the same name than theclass preceded by the character ~A class must have only one destructor method withoutarguments and returning void.When the scope of an object ends, the compilerautomatically calls its destructor. The destructor is alsocalled with delete. It can also be called explicitly:d.~Date();

Besides it’s allowed, it should never be called explicitly.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Destructors (2/2)

Example:

// Declaration~Date();

// ImplementationDate::~Date() {

// Free the allocated memory (nothing here)}

Important: The destructor of an object implicitly callsthe destructors of all its attributes.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Class attributes and methods (1/2)

The class attributes and methods are also calledstatic. They are represented underlined in UMLdiagrams.Class attributes have the same value for all the objectsof the class. They are like global variables for the class.Class methods can only access class attributes.

class Date {public:

static const int weeksInYear = 52;static const int daysInWeek = 7;static const int daysInYear = 365;static string getFormat();static boolean setFormat(string);

private:static string endOfTheWorld;

};

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Class attributes and methods (2/2)

Non simple type or non constant static attributes mustbe declared in the class, although they have to beinitialized outside.

// Date.h (inside the class declaration)static const string endOfTheWorld;

// Date.ccconst string Date::endOfTheWorld="2012";

Accessing public static attributes or methods fromoutside the class:

cout << Date::weeksInYear << endl; // Static attributecout << Date::getFormat() << endl; // Static method

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

The this pointer

The this pointer is a pseudovariable which is neitherdeclared nor modifiable.It’s an implicit argument received by all memberfunctions (excluding static functions).It points to the object which receives the message. It’susually omitted when accessing the attributes usingmember functions.It’s necessary when a parameter name needs to bedisambiguated, or when the object is passed to anested function.

void Date::setDay (int day) {// day=day; ERROR: ambiguousthis->day=day;cout << this->day << endl;

}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Constant methods

Constant methods are those that don’t modify thevalues of the object attributes.

int Date::getDay() const { // Constant methodreturn day;

}

Non-constant methods can’t be called by a constantobject. For instance, this code wouldn’t compile:

int Date::getDay() {return day;

}

int main() {const Date d(10,10,2011);cout << d.getDay() << endl;

}

get methods must be constant.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Friend functions (friend)

The private part of a class can only be seen by:The methods of that classFriend functions

A friend function does not belong to the class but it canaccess its private part.

class MyClass {friend void aFriendFunction(int, MyClass&);

public://...

private:int privateData;

};

void aFriendFunction(int x, MyClass& c) {c.privateData = x; // OK

}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Overload of input/output operators (1/3)

We can overload the input/output operator of any class:

MyClass obj;cin >> obj; cout << obj;

The problem is that these functions can’t be membersof MyClass, because the first operand is not an objectof that class (it’s an stream).Operators are overloaded using friend functions:

friend ostream& operator<< (ostream &o, const MyClass& obj);friend istream& operator>> (istream &o, MyClass& obj);

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Overload of input/output operators (2/3)

Declaration

class Date {friend ostream& operator<< (ostream &os, const Date& obj);friend istream& operator>> (istream &is, Date& obj);

public:Date (int day=1, int month=1, int year=1900);...

private:int day, month, year;

};

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Overload of input/output operators (3/3)

Implementation

ostream& operator<< (ostream &os, const Date& obj) {os << obj.day << "/" << obj.month << "/" << obj.year;return os;

}

istream& operator>> (istream &is, Date& obj) {char dummy;is >> obj.day >> dummy >> obj.month >> dummy >> obj.year;return is;

}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Object relations

Main relations between objects and classes

AssociationAggregationCompositionUse

Between objects

GeneralizationBetween classes

Most relations have a cardinality:One or more: 1..∗ (1..n)Zero or more: 0..∗ (0..n)Fixed value: m

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Association

Person Project* 1..*works in

The association express a relation (unidirectional orbidirectional) between the objects instantiated from thethe connected classes.The association direction is called navegability.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Aggregation and composition (1/2)

Aggregation and composition are All-Part relationswhere an object is part of another one. Unlikeassociation, they are asymmetric relations.The differences between aggregation and compositionare the relation strength. Aggregation is weaker thancomposition. Example:

Team

Player

Plane

Wing

* 2

1..11..*

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Aggregation and composition (2/2)

When the container object is destroyed and the relationis strong (composition), the objects that it contains arealso destroyed. Example: A wing belongs to a planeand it doesn’t make sense outside it (if a plane is sold,wings will also be included).In an aggregation relation this does not happen.Example: A team can be sold, but the players mayswitch to another club.Some relations can be considered either asaggregations or compositions, in function of the contextin which they are (for instance, the relation betweenbicycle and tyre).Some authors consider that the only differencebetween both concepts is the implementation; this way,a composition would be an ‘Aggregation by value’.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Implementation of the composition

The composition is the only relation that will be used inthe Programming 2 assignments.

class A { private: ! B b; ...};

class A { private: ! B b[10]; ...};

class A { private: ! vector<B> b; static const int N=10; ...};

class A { private: ! vector<B> b; ...};

A A A A

B B B B

-b-b1 -b -b0..*0..1010

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Use

The use is a non-persistent relation (all contactbetween objects is lost after the relation).

A class A uses a class B when it:uses any method of the class B.uses any instance of the class B as a parameter forsome of its methods.accesses to its private attributes (this can only be donewith friend classes).

Car Gas Station

float Car::Refuel(GasStation &g, float litres){

float amount=g.sellGas(litres, typeC);lgas= lgas+litres;return amount;

}

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Generalization (inheritance)

Inheritance allows to define a new class from anexisting class.It’s used when there are enough similarities, and mostof the features of the existing class are adequate for thenew class.

Mammal

Dog Cat

The subclasses Dog and Cat inherit the methods andattributes of the Mammal superclass.Inheritance allows to reuse features alreadyimplemented in other classes.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Exercises (1/3)

Exercise 1Implement the following class:

+ Coordenada (x: float = 0.0 , y: float = 0.0)+ Coordenada (const Coordenada &)+ ~Coordenada()+ <<const>> getX() : float+ <<const>> getY() : float+ setX(x: float) : void+ setY(y: float) : void+ <<friend>> operator << : ostream&

- x : float- y : float

Coordenada

Create the files Coordenada.cc, Coordenada.h, and a makefile tocompile them with a program principal.cc. The main() should ask theuser to introduce two numbers in order to create a coordinate and print itwith the output operator using the format x,y. Write the necessary codeto call all methods at least once.

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Exercises (2/3)

Exercise 2Implement the code corresponding to the following diagram:

+ Linea()+ <<const>> getSubtotal() : float+ <<const>> getCantidad() : int+ <<const>> getPrecio() : float+ <<const>> getDescripcion() : string+ setCantidad(cant : int) : void+ setPrecio(precio : float) : void+ setDescripcion(descripcion : string) : void

- cantidad : int- precio : float- descripcion : string

Linea

+ Factura(c: Cliente*, fecha : string) + anyadirProducto(cant : int, desc : string, prec : float) : void- getSigId() : int+ <<friend>> operator<< : ostream &

- sigId : int = 1+ IVA : const int = 18- fecha : string- id : int

Factura

1

+ Cliente(nom: string, dir : string, tel : string) + <<const>> getNombre() : string+ <<const>> getTelefono() : string+ <<const>> getDireccion(): string+ setNombre(nombre : string) : void+ setTelefono(telefono : string) : void+ setDireccion(direccion : string) : void

- nombre : string- direccion : string- telefono : string

Cliente

*

-cliente

-lineas

Unit 7

Introduction

Concepts

OOP in C++Syntax

Inline functions

Accessors

Canonical form

Constructors

Assignment

Copy constructors

Destructors

static

this

const

friend

I/O

RelationsAssociation

Aggregation andcomposition

Generalization

Exercises

Exercises (3/3)

Exercise 2 (continues)Develop a program to create a new bill (factura), add a product and printit. From the Factura constructor you should call to the methodgetSigid, that must return the value of sigid and increment it. This isan output example when a bill is printed:Factura nº: 12345Fecha: 18/4/2011

Datos del cliente----------------------Nombre: Agapito PiedralisaDirección: c/ Río Seco, 2Teléfono: 123456789

Detalle de la factura---------------------Línea;Producto;Cantidad;Precio ud.;Precio total--1;Ratón USB;1;8,43;8,432;Memoria RAM 2GB;2;21,15;42,33;Altavoces;1;12,66;12,66

Subtotal: 63,39 CIVA (18%): 11,41 CTOTAL: 74.8002 C