To prevent our programs to inherit multiple copies of a base class we can declare this base class as a virtual base class.



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

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

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

C++ Overloading, Constructors, Assignment operator

CSE 1020 Introduction to Computer Science I A sample nal exam

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

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

Advanced Data Structures

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

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

Calculating Area, Perimeter and Volume

Section 7.1 Solving Right Triangles

Comp151. Definitions & Declarations

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

Geometry - Calculating Area and Perimeter

COSC 181 Foundations of Computer Programming. Class 6

Perimeter. 14ft. 5ft. 11ft.

1. A student followed the given steps below to complete a construction. Which type of construction is best represented by the steps given above?

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

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

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

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.

39 Symmetry of Plane Figures

History OOP languages Year Language 1967 Simula Smalltalk

MODULE 17 POLYMORPHISM

Chapter 5 Functions. Introducing Functions

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

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

Estimating Angle Measures

The Area of a Triangle Using Its Semi-perimeter and the Radius of the In-circle: An Algebraic and Geometric Approach

Chapter 9 Delegates and Events

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Circumference Pi Regular polygon. Dates, assignments, and quizzes subject to change without advance notice.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

3 Representation in C++.

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement

How do you compare numbers? On a number line, larger numbers are to the right and smaller numbers are to the left.

Classes and Pointers: Some Peculiarities (cont d.)

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

Jzyk C++ cz 7. Jarosław Gramacki Instytut Informatyki i Elektroniki

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

EP241 Computer Programming

13 Classes & Objects with Constructors/Destructors

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

2006 Geometry Form A Page 1

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

Section 9-1. Basic Terms: Tangents, Arcs and Chords Homework Pages : 1-18

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

Computer Programming C++ Classes and Objects 15 th Lecture

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer

Compiler Construction

Geometry Progress Ladder

Tallahassee Community College PERIMETER

43 Perimeter and Area

Class 16: Function Parameters and Polymorphism

Selected practice exam solutions (part 5, item 2) (MAT 360)

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

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

Geometry Unit 6 Areas and Perimeters

Functional Programming in C++11

17. Friendship and Inheritance

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Geometry: Classifying, Identifying, and Constructing Triangles

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Konzepte objektorientierter Programmierung

UML: Classes -- Association

Characteristics of the Four Main Geometrical Figures

Perimeter is the length of the boundary of a two dimensional figure.

C++ INTERVIEW QUESTIONS

Grade 8 Mathematics Geometry: Lesson 2

Angle - a figure formed by two rays or two line segments with a common endpoint called the vertex of the angle; angles are measured in degrees

Transformations Worksheet. How many units and in which direction were the x-coordinates of parallelogram ABCD moved? C. D.

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Postulate 17 The area of a square is the square of the length of a. Postulate 18 If two figures are congruent, then they have the same.

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Introducing Variance into the Java Programming Language DRAFT

Canterbury Maps Quick Start - Drawing and Printing Tools

Definitions, Postulates and Theorems

Solids. Objective A: Volume of a Solids

The Interface Concept

ACT Math Vocabulary. Altitude The height of a triangle that makes a 90-degree angle with the base of the triangle. Altitude

Algebra III. Lesson 33. Quadrilaterals Properties of Parallelograms Types of Parallelograms Conditions for Parallelograms - Trapezoids

Surface Area Quick Review: CH 5

Heron s Formula. Key Words: Triangle, area, Heron s formula, angle bisectors, incenter

Math 0306 Final Exam Review

7.7 Case Study: Calculating Depreciation

Math 0980 Chapter Objectives. Chapter 1: Introduction to Algebra: The Integers.

Application Note C++ Debugging

Chapter 6 Notes: Circles

Algorithms, Flowcharts & Program Design. ComPro

Introduction to Programming Block Tutorial C/C++

COMPUTER SCIENCE 1999 (Delhi Board)

13.4 THE CROSS PRODUCT

Adding and Subtracting Positive and Negative Numbers

Transcription:

Virtual base classes To prevent our programs to inherit multiple copies of a base class we can declare this base class as a virtual base class. int i; ; class deriv1:virtual public base int j; ; class deriv2:virtual public base int k; ; class deriv3:public deriv1,public deriv2 int sum; ; deriv3 object; object.i=10; //.it s ok?? But without virtual base?? object.j=20; object.k=30; object.sum=object.i+object.j+object.k; cout<<object.i<<" + "<<object.j<<" + "<<object.k<<" is "<<object.sum<<endl; If the derivation of deriv1 and of deriv2 is not virtual, then we get errors of ambiguity at line 3 in the function main. Virtual functions A virtual function stays virtual no matter how many times is inherited. When a class inherits another class methods, it can happen that the class member names to be in conflict. 1

virtual void funct() cout<<" The function from the base class "<<endl; ; class deriv1:public base void funct() cout<<" The function from the class deriv1 "<<endl; ; class deriv2:public deriv1 void funct() cout<<"the function from the class deriv2 "<<endl; ; base *p, b; deriv1 d1; deriv2 d2; p=&b; //indicating??? p->funct(); //which of the functions will be called? p=&d1; p->funct(); //?? p=&d2; p->funct(); //?? What happens if the function funct( ) from the base class is not virtual??? Pure virtual functions A pure virtual function is a function that is declared in the base class and that requires its own implementation of it in the derived class. Prototype: virtual data_type function_name(parameters)=0; 2

virtual void funct() cout<<" The base class "<<endl; virtual void functv(void)=0; ; class deriv:public base void funct() cout<<" :) "<<endl; virtual void functv(void) cout<<"pure virtual function "<<endl; ; base *p=new deriv; p->funct(); p->functv(); Abstract classes When a class contains at least one pure virtual function, then the class is called abstract. C++ will not allow you to create a variable whose type is an abstract class. A class which contains only pure virtual member functions is called interface. Polymorphism Is the ability of an object to take many forms. This is possible in C++ by using virtual functions. The same pointer can indicate to different classes in order to perform different operations. #include <string> virtual int add(int a,int b) 3

cout<<" add from the base class "<<endl; return (a+b); virtual int subtract(int a,int b) cout<<" subtract from the base class "<<endl; return (a-b); virtual int multip(int a,int b) cout<<" multiplication from the base class "<<endl; return (a*b); ; class deriv1:public base int multip(int a,int b) cout<<" multiplication from the class deriv1"<<endl; return (a*b); ; class deriv2:public base int subtract(int a, int b) cout<<" subtraction from the class deriv2"<<endl; return (abs(a-b)); ; base *p=new deriv1; cout<<p->add(300,299)<<" "<<p->subtract(799,200)<<" "<<p->multip(599,1)<<endl; p=new deriv2; cout<<p->add(222,111)<<" "<<p-> subtract (18,288)<<" "<<p-> multip (398,2)<<endl; Class hierarchies Exercises: 1. Implement a class hierarchies which allows working with geometrical shapes. Requests: -Define an abstract class Shape. A shape is characterized by a name and has a method GetName( ) in order to obtain the name. Also, the class Shape contains an abstract method GetArea( ) which will return its area; 4

- Define a class Circle, derived from the class Shape. The class Circle will have a constructor receiving the name of the circle, the circle center coordinates and the radius. The class Circle will have a method to overload the method GetArea() from the class Shape; - Define another abstract class PolygonalShape, derived from the class Shape. The class PolygonalShape class will define an interface for working with shapes made of points and segments. The PolygonalShape class will have an abstract method called GetPointsCount() in order to read the number of points of the figure. The class PolygonalShape will overload the indexing operator []. You have to declare as a virtual function operator[] in the class PolygonalShape; - Define a class Triangle, derived from the class PolygonalShape. The Triangle class will have a constructor receiving the name of the triangle and the coordinates of three points of the triangle. The Triangle class overloads GetArea() and GetPointsCount() and the operator []; -Define a class Rectangle, derived from the class PolygonalShape. The Rectangle class will have a constructor receiving the name and the coordinates of two opposite points (corners) of the rectangle. The Rectangle class overloads the methods GetArea(), GetPointsCount() and the operator []; - To work with points define a class Point that will hold the coordinates of a point. The Point class will have a constructor that will get the coordinates of a point. Built in the class Point two methods GetX() and GetY() in order to read the coordinates. Add also the method DistanceTo(Point& other) which will return the distance from one point to another point. Use the class Point class in the classes Circle, Triangle and Rectangle (composition relationship); The function main is: int main() Circle c("c", 2.5, 2.5, 2.5); Triangle t("abc", 0, 0, 5, 0, 0, 5); Rectangle r("pqrs", 0, 0, 5, 5); int i; cout << "---=== SHAPES ===---" << endl; Shape* shapes[3]; shapes[0] = &c; shapes[1] = &t; shapes[2] = &r; for (i=0; i < 3; i++) cout << shapes[i]->getname() << ": area=" << shapes[i]- >GetArea() << endl; cout << "---=== POLYGONAL SHAPES ===---" << endl; PolygonalShape* polyshapes[2]; polyshapes[0] = &t; polyshapes[1] = &r; for (i=0; i < 2; i++) cout << polyshapes[i]->getname() << ": area=" << polyshapes[i]- 5

>GetArea() << ", pointscount=" << polyshapes[i]->getpointscount() << ", points:"; for (int j=0; j < polyshapes[i]->getpointscount(); j++) cout << " " << (*polyshapes[i])[j]; cout << endl; return 0; The output should be: ---=== SHAPES ===--- C: area=45.3416 ABC: area=12.5 PQRS: area=35.3553 ---=== POLYGONAL SHAPES ===--- ABC: area=12.5, pointscount = 3, points: (0, 0) (5, 0) (0, 5) PQRS: area=35.3553, pointscount = 4, points: (0, 0) (0, 5) (5, 5) (5, 0) Hint 1) When implementing the indexing operator (operator[]) for the Triangle and Rectangle classes, you must handle the situation when an invalid index is passed to the operator. For example for a Triangle it only makes sense to pass 0, 1 or 2 as index value, since we have only three points in a triangle. Also for a Rectangle it only makes sense to pass 0, 1, 2 or 3 as an index value, since we have only four points in a Rectangle. Define a static member of type Point in the PolygonalShape class. Call this member BAD_POINT and initialize it with whatever values you consider (for example a point with negative coordinates). Then, when overloading operator[], if the index value is invalid, just return a reference to BAD_POINT. Make the BAD_POINT member protected, so that it can be accessed from the derived classes. 2) Before starting the implementation, create the UML class diagram for an overall structure of the system. 6

The class hierarchy: (the UML diagram) 7