Where do we stand on inheritance?

Size: px
Start display at page:

Download "Where do we stand on inheritance?"

Transcription

1 In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class <derived-class-name>:public <base class-name> <derived class member functions> <derived class member data> Derived classes inherit: public and protected methods and data members of the base class Derived classes do not inherit: private data members and methods of the base class friend functions of the base class constructor(s) and the destructor of the base class base class assignment operator

2 Types of Inheritance We ve said that to declare a derived class: class <derived-class-name>:public <base class-name> <derived class member functions> <derived class member data> In fact, the full syntax is class <derived-class-name>:<access specifier> <base class-name> <derived class member functions> <derived class member data> The access specifier can be public (in this case, public and protected members of the base class become public and protected members of the derived class and private members are only accessible through public/protected members of the base class) protected (in this case, public and protected members of the base class become protected members of the derived class) private (in this case public and protected members of the base class become private members of the derived class) We almost never use protected and private inheritance!!

3 We d defined and implemented a standard C++ class hierarchy class BankAccount public: void Deposit (double dep); int AcctNum(); double Balance(); int getcust(); int AcctNumber; int custid; double Bal; class SuperPlus: public Checking public: SuperPlus(int AcctNo = 0000, int cust = 000, double Bal = 0, double Min = 5000, double Chg =.5, double Rate = 10); void Addinterest(); double InterestRate; class Checking:public BankAccount public: Checking (int AcctNum = 0000, int custid = 000, double Bal = 0, double Min = 1000, double Chg =.5); void CashCheck(float Amt); double MinBal; double Charge; class Savings:public BankAccount public: Savings( int AcctNumber = 0, int custid = 000, double Bal = 0, double Rate = 10); void AddInterest(); void Withdraw(double Amt); double InterestRate; L17 Feb. 24, 2010 friends and software reuse

4 Differences: Managed vs. Unmanaged classes If we are working in the CLR, there are some issues that are significant: an unmanaged type cannot derive from a managed type a ref class can only inherit from a ref class or interface class More about interface classes later the bottom line is that you need to keep a hierarchy compatible: all standard C++ or all CLR Working with managed types: no default arguments are allowed for member functions of managed types or generic functions this means that you have to make a default constructor that explicitly assigns the default values for data members instead of using the default argument syntax of standard C++ it also may mean that you need some extra constructors for situations in which you may want to do some default, some supplied data member values (e.g. accounts and values in the banking example)

5 A ref version of the banking class we discussed last time ref class BankAccount public: BankAccount (); BankAccount (int AcctNum, int cust); BankAccount (int AcctNum, int custid, double Bal); void Deposit (double dep);// deposit method int AcctNum(); // get account number double Balance(); // get balance int getcust(); // get customer SSN ref class Savings:public BankAccount public: Savings(); Savings( int AcctNumber, int custid); Savings( int AcctNumber, int custid, double Bal, double Rate); void AddInterest(); // add interest to balance void Withdraw(double Amt); // subtract withdrawal BankAccount (BankAccount % a); BankAccount operator = (BankAccount a); double InterestRate; int AcctNumber; int custid; double Bal;

6 The ref version of the banking class (cont.) ref class Checking:public BankAccount public: Checking(); Checking (int AcctNum, int custid); Checking (int AcctNum, int custid, double Bal, double Min, double Chg); void CashCheck(float Amt); Checking (Checking % a); Checking operator = (Checking a); double MinBal; // min bal to avoid charges double Charge; // per check charge ref class SuperPlus: public Checking public: // Constructors SuperPlus(); SuperPlus(int AcctNo, int cust); SuperPlus(int AcctNo, int cust, double Bal, double Min, double Chg, double Rate); // add interest to the balance void Addinterest(); double InterestRate;

7 ref Banking class hierarchy -- Notice that we have assignment and copy constructor, and other constructors defined for the base class BankAccount and for the derived class Checking, are we OK? Not really an assignment involving derived classes Savings and SuperPlus will generate an error saying that the operator = is not available Moral of the story: when dealing with ref classes in.net: if you have any intention of doing assignment, you must define an overloading of the assignment operator for the class this means that you must also define a copy constructor for the class it s good practice to define a destructor as well Assignment operators are not inherited by derived classes

8 Base Classes, and Derived Classes Even though a derived class object (like a SuperPlus account, for example) is-a base class object (i.e. a Checking account), the derived class type and the base class type are different types With public inheritance, derived class objects can be treated as base class objects the derived class has the full set of base class data members, after all It is not true, though, that base class objects can be treated as derived class objects the non-corresponding derived class data members would be undefined (unless care were taken to handle the situation) Look at the structure of Checking type objects (in a minute)! This means that assigning a derived class object to an object of a corresponding base class then trying to reference derived class (only) members in the new base class object will generate errors

9 BankAccount int AcctNumber; int custid; double Bal; Remember the Banking hierarchy: BankAccount AcctNumber custid Bal Checking:public BankAccount double MinBal; double Charge; SuperPlus: public Checking double InterestRate; Savings:public BankAccount double InterestRate; L17 Feb. 24, 2010 friends and software reuse Checking AcctNumber custid Bal MinBal Charge Savings AcctNumber custid Bal InterestRate SuperPlus AcctNumber custid Bal MinBal Charge InterestRate

10 Backpatching a hole Casting to a type I ve noticed that some of you are casting to types Converting an expression of one type to another type is called type casting There are two ways to do type casting: Implicitly: C++ does implicit type conversion when a value is copied to a compatible type For example, int x = 3.5 / 1.5 the rhs expression is a floating point expression and when the assignment is done it is automatically converted to an int. Explicitly: Many conversions, especially those that imply a different interpretation of the value, need to be explicitly converted. C++ has four specific casting operators: dynamic_cast reinterpret_cast static_cast const_cast

11 dynamic_cast Syntax: dynamic_cast <new_type> (expression) Usage: can be used only with pointers and references to objects purpose is to ensure that the result of the type conversion is a valid complete object of the right class is always successful when we cast a class to one of its base classes Example: class Base class Der: public Base Base b; Base* pb; Der d; Der* pd; pb = dynamic_cast<base*>(&d); pd = dynamic_cast<der*>(&b); // ok: derived-to-base // wrong: base-to-derived

12 static_cast Syntax: static_cast <new_type> (expression) Usage: can perform conversions between pointers to related classes from the derived class to its base from a base class to its derived. ensures that at least the classes are compatible if the proper object is converted no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type (unlike dynamic_cast) up to the programmer to ensure that the conversion is safe plus side: the overhead of the type-safety checks of dynamic_cast is avoided. can also be used to perform any other non-pointer conversion that could also be performed implicitly Example: class Base class Der: public Base Base * a = new Base; Der * b = static_cast<der*>(a); double pi= ; int i = static_cast<int>(pi);

13 reinterpret_cast Syntax: reinterpret_cast <new_type> (expression) Usage: converts any pointer type to any other pointer type, even of unrelated classes result is a simple binary copy of the value from one pointer to the other. all pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked. can also cast pointers to or from integer types format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is guaranteed to be able to be cast back to a valid pointer. conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ and are low-level operations whose interpretation results in code which is generally system-specific, and thus non-portable. that s why you don t see this one much! Example: class A class B A * a = new A; B * b = reinterpret_cast<b*>(a); This is legal, but it does not make a lot of sense -- we have a pointer that points to an object of an incompatible class -- dereferencing it is unsafe

14 Syntax const_cast const_cast <new_type> (expression) Usage manipulates the constness of an object, either to be set or to be removed. Example: void foo(char *); const char *x = "abcd"; foo(const_cast<char *>(x)); This strips the const-ness from the variable x useful in those rare circumstances when you have a const thing that you want to use as an argument to a non const function or method

15 Pointers, Base Classes, and Derived Classes With public inheritance, a pointer (or tracking handle) to a derived class object can be implicitly converted to a pointer (or tracking handle) to a base-class object why? because a derived class object is a base class object, too There are four ways of mixing and matching base class pointers (tracking handles) and derived class pointers (tracking handles) with base class objects and derived class objects: base-class object base class pointer derived-class object derived class pointer derived-class object base class pointer base-class object derived class pointer

16 Homework 5 The beginnings of a class structure is posted to Moodle The base class and some derived classes The assignment involves you defining and implementing some more derived classes and doing a small application based on them. The idea is to give you some practice with an inheritance hierarchy and using it. There will be a Moodle quiz on inheritance that will be part of this assignment. All is due on Friday of next week (BEFORE BREAK so you don t have an assignment hanging over your head going into break)

17 Pointers, Base Classes, and Derived Classes (cont.) Referring to a base class object with a base class pointer or tracking handle is fine Referring to a derived class object with a derived class pointer or tracking handle is fine Referring to a derived class object with a base class pointer or tracking handle is safe the derived class object is-a base class thing, too if you try to refer to derived-class-only members through the base class pointer, a syntax error occurs Referring to a base class object with a derived class pointer or tracking handle is an error the derived class pointer has to be cast to a base class pointer or tracking handle first

18 Some Examples (class definitions) class point public: point(); point (double x, double y); point (point &p); point operator = (point p); void setpoint(double, double); double get_x(); double get_y(); double x, y; class circle : public point public: circle (double r = 0.0, int x = 0, int y = 0); void setradius(double); double getradius(); double area(); double radius;

19 #include "stdafx.h" #include "PointCircle.h" point::point() x = -1.0; y = -1.0;} Examples (point class implementation) Code placed in PointCircle.cpp point::point (double xval, double yval) setpoint (xval, yval);} // overloaded constructor void point::setpoint(double xval, double yval) x = xval; y = yval; } double point::get_x()return x;} double point::get_y() return y;} point::point (point &p) double xval = p.get_x(); double yval = p.get_y(); setpoint (xval, yval); } // copy constructor point point::operator = (point p) // overloading of = double x = p.get_x(); double y = p.get_y(); setpoint(x, y); return *this; }

20 // within PointCircle.cpp Examples (circle class implementation) circle::circle(double r, int a, int b) : point(a, b) setradius(r);} void circle::setradius (double r) radius = (r >= 0? r : 0); } double circle::getradius() return radius; } double circle::area() return * radius * radius; }

21 Derived class and Base class Pointers #include "stdafx.h" #include <iostream> using namespace System; using namespace std; #include "PointCircle.h" int main() } point *pointptr, p(10,10); // p is a point at (10,10) circle *circleptr, c(5, 20, 20); // c is a circle of radius // 5 centered at (20, 20) // treating a Circle as a Point: pointptr = &c; // assign address of the Circle to pointptr circleptr = &c; cout << pointptr -> get_x() << ", " << pointptr -> get_y(); return 0; BUT An attempt to access the radius of the circle through pointptr will generate a syntax error! double cr = circleptr->getradius(); double r = pointptr->getradius(); // is just fine // generates a syntax error

22 Derived class and Base class Pointers (cont.) int main() point *pointptr, p(10,10); // p is a point at (10,10) circle *circleptr, c(5, 20, 20); // c is a circle of radius // 5 centered at (20, 20) // treating a Circle as a Point: pointptr = &c; // assign address of the Circle to pointptr // cast the base class pointer to a derived class pointer circleptr = static_cast <circle *> (pointptr); cout << "\n circle c via circleptr: " << circleptr->getradius() << "\n area of circle via circleptr: " << circleptr-> area() << endl; // treating a point as a circle?? pointptr = &p; // cast base class pointer to a derived class pointer circleptr = static_cast <circle *> (pointptr); cout << "\n point p (xval, yval) via circleptr: (" << circleptr->get_x()<<", " << circleptr->get_y()<< ")" << endl << "radius of object circleptr points to: " << circleptr-> getradius() << "\n area of the object circleptr points to: " << circleptr-> area() << endl; return 0; } Reference classes behave in pretty much the same way

23 What s going on here and why is it important? When a class hierarchy is defined, the base class provides a set of data elements and methods that are inherited by all classes derived from it some features of the base class are not inherited by the derived classes, including: constructor(s) and destructor friend functions Each class (whether derived or otherwise) has to have at least a default constructor and a destructor. When we instantiate a derived class object: a chain of constructor calls occurs: before it does its own tasks, the constructor of a derived class first either explicitly or implicitly calls its base class constructor then it dos its own tasks if the base class was itself derived, it follows the same discipline: call its base class constructor, etc. On garbage collection, destructors are called in reverse order

24 What s going on here and why is it important? (cont.) We can access derived class objects through base class-type pointers as long as we don t try to access those elements that are derived-class only (i.e. not base-class) elements If a base-class pointer refers to a derived-class object, we can cast the base-class pointer to the object s actual type and then manipulate the derived-class-only elements (but we do have to do the cast)

Scope. Scope is such an important thing that we ll review what we know about scope now:

Scope. Scope is such an important thing that we ll review what we know about scope now: Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,

More information

Dr. Md. Humayun Kabir CSE Department, BUET

Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2 C++

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Chapter 19 - C++ Inheritance

Chapter 19 - C++ Inheritance Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions

More information

COEN244: Polymorphism

COEN244: Polymorphism COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Chapter 19 C++ Inheritance

Chapter 19 C++ Inheritance Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p

More information

CS11 Advanced C++ Fall Lecture 7

CS11 Advanced C++ Fall Lecture 7 CS11 Advanced C++ Fall 2006-2007 Lecture 7 Today s Topics Explicit casting in C++ mutable keyword and const Template specialization Template subclassing Explicit Casts in C and C++ C has one explicit cast

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts. asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification

More information

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int, Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class

More information

G52CPP C++ Programming Lecture 15

G52CPP C++ Programming Lecture 15 G52CPP C++ Programming Lecture 15 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 IMPORTANT No optional demo lecture at 2pm this week Please instead use the time to do your coursework I

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

15: Polymorphism & Virtual Functions

15: Polymorphism & Virtual Functions 15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism Review from Lecture 22 Added parent pointers to the TreeNode to implement increment and decrement operations on tree

More information

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns This Advanced C++ Programming training course is a comprehensive course consists of three modules. A preliminary module reviews

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

Module 7 b. -Namespaces -Exceptions handling

Module 7 b. -Namespaces -Exceptions handling Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides

More information

C++ Inheritance II, Casting

C++ Inheritance II, Casting C++ Inheritance II, Casting CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

C++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield

C++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield C++ Programming Classes Michael Griffiths Corporate Information and Computing Services The University of Sheffield Email m.griffiths@sheffield.ac.uk Presentation Outline Differences between C and C++ Object

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

CS105 C++ Lecture 7. More on Classes, Inheritance

CS105 C++ Lecture 7. More on Classes, Inheritance CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.

More information

ECE 3574: Dynamic Polymorphism using Inheritance

ECE 3574: Dynamic Polymorphism using Inheritance 1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

C++ Inheritance II, Casting

C++ Inheritance II, Casting C++ Inheritance II, Casting CSE 333 Summer 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11 CHAPTER 9 INHERITANCE 1 Illustrations List (Main Page) Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig. 9.10 Fig. 9.11 Some simple inheritance examples. An inheritance

More information

Ch. 3: The C in C++ - Continued -

Ch. 3: The C in C++ - Continued - Ch. 3: The C in C++ - Continued - QUIZ What are the 3 ways a reference can be passed to a C++ function? QUIZ True or false: References behave like constant pointers with automatic dereferencing. QUIZ What

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

C++ Casts and Run-Time Type Identification

C++ Casts and Run-Time Type Identification APPENDIX K C++ Casts and Run-Time Type Identification Introduction There are many times when a programmer needs to use type casts to tell the compiler to convert the type of an expression to another type.

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

More information

CS 162 Intro to CS II. Structs vs. Classes

CS 162 Intro to CS II. Structs vs. Classes CS 162 Intro to CS II Structs vs. Classes 1 Odds and Ends Assignment 1 questions Why does the delete_info have a double pointer to states as a parameter? Do your functions have to be 15 or under? Anymore???

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques 1 CPSC2620 Advanced Programming Spring 2003 Instructor: Dr. Shahadat Hossain 2 Today s Agenda Administrative Matters Course Information Introduction to Programming Techniques 3 Course Assessment Lectures:

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

Abstract Data Types (ADT) and C++ Classes

Abstract Data Types (ADT) and C++ Classes Abstract Data Types (ADT) and C++ Classes 1-15-2013 Abstract Data Types (ADT) & UML C++ Class definition & implementation constructors, accessors & modifiers overloading operators friend functions HW#1

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CS11 Introduction to C++ Fall Lecture 7

CS11 Introduction to C++ Fall Lecture 7 CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,

More information

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

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

PROGRAMMING IN C AND C++:

PROGRAMMING IN C AND C++: PROGRAMMING IN C AND C++: Week 1 1. Introductions 2. Using Dos commands, make a directory: C:\users\YearOfJoining\Sectionx\USERNAME\CS101 3. Getting started with Visual C++. 4. Write a program to print

More information

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer? Midterm 2 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer? A handle class is a pointer vith no visible type. What s wrong with

More information

Operators. The Arrow Operator. The sizeof Operator

Operators. The Arrow Operator. The sizeof Operator Operators The Arrow Operator Most C++ operators are identical to the corresponding Java operators: Arithmetic: * / % + - Relational: < = >!= Logical:! && Bitwise: & bitwise and; ^ bitwise exclusive

More information

Chapter 20 - C++ Virtual Functions and Polymorphism

Chapter 20 - C++ Virtual Functions and Polymorphism Chapter 20 - C++ Virtual Functions and Polymorphism Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes 20.5 Polymorphism

More information

Comp151. Inheritance: Initialization & Substitution Principle

Comp151. Inheritance: Initialization & Substitution Principle Comp151 Inheritance: Initialization & Substitution Principle Initializing Base Class Objects If class C is derived from class B which is in turn derived from class A, then C will contain data members of

More information

C++ Constructor Insanity

C++ Constructor Insanity C++ Constructor Insanity CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Inheritance (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1 CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining

More information

Simplest version of DayOfYear

Simplest version of DayOfYear Reminder from last week: Simplest version of DayOfYear class DayOfYear { public: void output(); int month; int day; }; Like a struct with an added method All parts public Clients access month, day directly

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015 C++ Coding Standards and Practices Tim Beaudet (timbeaudet@yahoo.com) March 23rd 2015 Table of Contents Table of contents About these standards Project Source Control Build Automation Const Correctness

More information

Industrial Programming

Industrial Programming Industrial Programming Lecture 4: C# Objects & Classes Industrial Programming 1 What is an Object Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a

More information

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes What is an Object Industrial Programming Lecture 4: C# Objects & Classes Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a person called John Objects

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples: Unit IV Pointers and Polymorphism in C++ Concepts of Pointer: A pointer is a variable that holds a memory address of another variable where a value lives. A pointer is declared using the * operator before

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism SI-1200 ata Structures Fall 2017 Lecture 25 ++ Inheritance and Polymorphism Review from Lecture 24 (& Lab 12!) Finish hash table implementation: Iterators, find, insert, and erase asic data structures

More information

C++ : Object Oriented Features. What makes C++ Object Oriented

C++ : Object Oriented Features. What makes C++ Object Oriented C++ : Object Oriented Features What makes C++ Object Oriented Encapsulation in C++ : Classes In C++, a package of data + processes == class A class is a user defined data type Variables of a class are

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

CS11 Introduction to C++ Fall Lecture 1

CS11 Introduction to C++ Fall Lecture 1 CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete. CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

Function Declarations. Reference and Pointer Pitfalls. Overloaded Functions. Default Arguments

Function Declarations. Reference and Pointer Pitfalls. Overloaded Functions. Default Arguments Reference and Pointer Pitfalls Function Declarations Never return a reference or a pointer to a local object. The return value will refer to memory that has been deallocated and will be reused on the next

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 3 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Inheritance S Software reuse inherit a class s data and behaviors and enhance with new capabilities.

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire

More information

Assumptions. History

Assumptions. History Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout

More information

CSE 333 Lecture C++ final details, networks

CSE 333 Lecture C++ final details, networks CSE 333 Lecture 19 -- C++ final details, s Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW3 is due in 5 days! - we re up to 6 bugs for you to patch

More information