QUIZ. How could we disable the automatic creation of copyconstructors

Similar documents
QUIZ. How could we disable the automatic creation of copyconstructors

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?

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

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

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

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

QUIZ Friends class Y;

Ch. 10: Name Control

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

QUIZ. Can you find 5 errors in this code?

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

Fast Introduction to Object Oriented Programming and C++

VIRTUAL FUNCTIONS Chapter 10

Ch02. True/False Indicate whether the statement is true or false.

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

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

Ch. 12: Operator Overloading

Lecture 13: more class, C++ memory management

Absolute C++ Walter Savitch

Polymorphism Part 1 1

CMSC202 Computer Science II for Majors

1: Introduction to Object (1)

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

Software Design and Analysis for Engineers

Instantiation of Template class

Lecture 14: more class, C++ streams

Object-Oriented Programming, Iouliia Skliarova

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

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

Module 10 Inheritance, Virtual Functions, and Polymorphism

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Data Abstraction. Hwansoo Han

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Inheritance and Interfaces

C++ Important Questions with Answers

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Inheritance Ch

QUIZ. What are 3 differences between C and C++ const variables?

Computer Science 306 Study Guide

Reusable and Extendable Code. Composition Example (1) Composition Example (2) CS183-Su'02-Lecture 8 17 June by Eric A. Durant, Ph.D.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Software Design and Analysis for Engineers

What are the characteristics of Object Oriented programming language?

QUIZ. Source:

Problem Solving with C++

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 1 Getting Started

Chapter 14. Inheritance. Slide 1

CS 162, Lecture 25: Exam II Review. 30 May 2018

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

G52CPP C++ Programming Lecture 9

Chapter 5 Object-Oriented Programming

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

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)


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

COP 3330 Final Exam Review

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

Object Orientated Analysis and Design. Benjamin Kenwright

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

CS-202 Introduction to Object Oriented Programming

PIC 10A Objects/Classes

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

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Supporting Class / C++ Lecture Notes

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

Chapter 14 Inheritance. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

ECE 3574: Dynamic Polymorphism using Inheritance

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

G52CPP C++ Programming Lecture 13

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Lecturer: William W.Y. Hsu. Programming Languages

CS 251 Intermediate Programming Inheritance

Object-Oriented Design (OOD) and C++

G52CPP C++ Programming Lecture 20

CSE 333 Midterm Exam 2/14/14

Interview Questions of C++

Lecture Notes on Programming Languages

Object Oriented Programming

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Introduction to Programming

CSE 303: Concepts and Tools for Software Development

ITI Introduction to Computing II

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

Lecture Topics. Administrivia

These are notes for the third lecture; if statements and loops.

CS18000: Problem Solving And Object-Oriented Programming

CS3157: Advanced Programming. Outline

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

ITI Introduction to Computing II

Java Object Oriented Design. CSC207 Fall 2014

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

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

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.

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

Transcription:

QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example.

QUIZ How is the overloaded assignment operator different from all other overloaded operators in C++?

QUIZ Show in a code example how to disable the automatic creation of the overloaded assignment operator post- C++11. The class is named Foo.

Ch. 14: Inheritance & Composition

Remember composition

Composition If embedded object is private, it will be accessed through member (or friend) functions

Draw the UML diagram, as learned in ch.1! Composition multi-level example

Inheritance Base class, from which Y inherits UML diagram

Inheritance The default is private inheritance During inheritance, everything defaults to private. If the base class were not preceded by public, it would mean that all of the members of the base class, private and public would be private in the derived class. Examples on next slide

Explaining public and private in inheritance (see protected later!)

Inheritance adding new functions change( ) we can add completely new functions.

Inheritance redefining functions set( ) we can redefine functions from the base class. If function is redefined, we can still call the base-class version using the scope resolution operator!

Inheritance redefining functions A note on language: redefining functions in a derived class is mostly referred to today as overriding; this includes the C++ standards. (Redefining is used when we talk about typedef or namespaces.) Unfortunately, the matter is further muddled by the existence of the override identifier (since C++11 it applies only to virtual functions).

Does this colon remind us of something?

Answer: The constructor initializer list Indeed, the constructor initializer list is used to initialize the members of the parent class! Example on next slide

Using the constructor initializer list to initialize members of the parent class

text Using the constructor initializer list to initialize members of the parent class There s no way to get to the opening brace of the constructor without some constructor being called for all the member objects and base-class objects, even if the compiler must make a hidden call to a default constructor. This is a further enforcement of the C++ guarantee that no object (or part of an object) can get out of the starting gate without its constructor being called.

text Automatic destructor calls Although you are often required to make explicit constructor calls in the initializer list, you never need to make explicit destructor calls because there s only one destructor for any class, and it doesn t take any arguments. However, the compiler still ensures that all destructors are called, and that means all of the destructors in the entire hierarchy, starting with the most-derived (bottom) destructor and working up to the root.

text Automatic destructor calls Note well: Constructors and destructors are quite unusual in that every one in the hierarchy is called, whereas with a normal member function only that function is called, but not any of the baseclass versions.

QUIZ Write a constructor for class Bar that initializes the data member and announces itself.

Solution

Declare a class MyType2 derived from Bar that has a new private data member of type integer, m. QUIZ

Solution

QUIZ Write a constructor for MyType2 that initializes i with a value, and m with the same value incremented by one.

Solutions

Can Bar s constructor also be moved from the initializer list inside the body? QUIZ

In other words: It s too late! Solution

QUIZ Write a print() member function for MyType2 that prints both i and m.

User code on next slide Solution

EOL 1

Order of constructor & destructor calls If an object has several sub-objects, each of them possibly with sub-objects of their own: construction starts at the very root of the class hierarchy at each level, the base class constructor is called first, followed by the member object constructors. The destructors are called in exactly the reverse order of the constructors. example

First, let s grok the macro used to define classes in the program C14:Order.cpp It has to be only one logical line for the preprocessor! "Stringification Operator" converts a token into a string, escaping any quotes or backslashes. Write the expanded form when ID is replaced with Base1 by the preprocessor!

First, let s grok the macro used to define classes in the program C14:Order.cpp Placeholder argument avoids default constructor! Remember character array concatenation from ch.2!

First, let s grok the macro used to define classes in the program C14:Order.cpp Some programmers like to put it here, so the code looks like a valid class declaration, but it adds to Innocuous here, but can cause problems before else statement, since it counts as a null statement. It is considered best practice to swallow the semicolon.

This is one of the many reasons why macros are tricky! This is an economical way to create many similar classes with diferent names (for testing purposes).

Now let s see the derived classes in the program C14:Order.cpp Draw the UML diagram!

Now let s see the derived classes in the program C14:Order.cpp

Now let s see the derived classes in the program C14:Order.cpp

text Name hiding If you inherit a class and provide a new definition for one of its member functions, the function from the base class is hidden. If the function was overloaded in the base class, all the overloaded versions are hidden. (This happens whether we provide the exact signature and return type or not.) examples

Redefinition, so g() from the base class is hidden

Hides both overloaded f() functions from the base!

However, it s still possible to access the overloaded f() from the base using the scope-resolution operator!

Return value does not make a difference; just like derived2, it hides both overloaded f() functions from the base!

Argument type does not make a difference; just like derived2, it hides both overloaded f() functions from the base!

Functions that don t automatically inherit Language twist: What is meant is that the functions are not automatically inherited. 1. Constructors and destructors deal with the creation and destruction of an object, and they can know what to do with the aspects of the object only for their particular class, so all the constructors and destructors in the hierarchy below them must be called. Thus, they are not inherited, and must be created specially for each derived class.

Functions that don t automatically inherit 2. The operator= doesn t inherit either, because it performs a constructor-like activity. In lieu of inheritance, these functions are synthesized by the compiler if you don t create them yourself, using memberwise initialization and memberwise assignment, respectively (as described in Chapters 11 and 12).

Inheritance and static member functions As far as inheritance is concerned, static member functions act the same as non-static ones: They are inherited automatically into the derived class. If you redefine a static member, all the other overloaded functions in the base class are hidden.

text protected In an ideal world, private members would always be hard-and-fast private, but in real projects there are times when you want to make something hidden from the world at large and yet allow access for members of derived classes. The protected keyword is a nod to pragmatism; it says, This is private as far as the class user is concerned, but available to anyone who inherits from this class. Example on next slide

No need for public inheritance anymore, we can be more selective and allow the derived class access to only those members of the base class that are really needed. This makes the code safer!

Individual work for next time: Read and understand the section Combining composition & inheritance End-of-chapter exercises 1, 2 EOL 2

QUIZ: Explain how methods are hidden during inheritance

QUIZ: Explain how methods are hidden during inheritance Solution If we redefine a member function foo, all the overloaded member functions foo in the base class are hidden.

Important application of inheritance: Example: subtyping We want to create a type of ifstream object that not only opens a file but also keeps track of the name of the file. We try to use composition and embed both an ifstream and a string into the new class:

.

Unfortunately, we run into this problem: The member functions of the embedded objects are not immediately available, e.g. we need to say

Solution: Derive a class from ifstream

Added benefit: non-member functions like getline( ) that expect an ifstream can also work with an FName2. That s because an FName2 is a type of ifstream; it doesn t just contain one! This is called

Upcasting The relationship between the child class and parent class can be summarized by saying, The child class is a type of the parent class. Parent (base) class Child (derived) class

Upcasting and the copy-constructor

Draw the UML class diagram!

No explicit copy-constructor!

QUIZ In what order are the initializations performed when a Child object is created?

How does the compiler synthesize the copy-constructor? As expected, top-down: Conclusion: If you allow the compiler to synthesize a copy-constructor for a derived class, it will automatically call the base-class copyconstructor, and then the copy-constructors for all the member objects (or perform a bitcopy on built-in types)

Extra-credit EOL 3

SKIP Operator overloading & inheritance

Deleted functions & inheritance Not in text. Only applies to C++11 and later.

Deleted functions & inheritance Not in text. Only applies to C++11 and later.

A philosophical note Changes that can be made in a derived class: Think of biological evolution

text Multiple inheritance (MI) [ ] inherit from more than one class at a time. Indeed you can, but whether it makes sense as part of a design is a subject of continuing debate. One thing is generally agreed upon: You shouldn t try this until you ve been programming quite a while and understand the language thoroughly.

Typical use of MI Remember subtyping What if we need the functionality from two (or more) existing classes, each fairly complex? In the literature, this is known as combining libraries. Example on next slides

MI opens the possibility of many ambiguities, e.g. what if both base classes have members (data or/and functions) with the same name? See vol.2 of our text for details.

You turn! Declare a class C that inherits from both A and B. Create a C object in the main program.

Source: http://www.geeksforgeeks.org/multiple-inheritance-in-c/ Solution

Incremental development One of the advantages of inheritance and composition is that these support incremental development by allowing you to introduce new code without causing bugs in existing code. If bugs do appear, they are isolated within the new code.

Incremental development By inheriting from (or composing with) an existing class, [ ] you leave the existing code that someone else may still be using untouched and unbugged. If a bug happens, you know it s in your new code, which is much shorter and easier to read than if you had modified the body of existing code.

Individual work for next time: Read the subsections Choosing composition vs. inheritance Composition vs. inheritance (revisited) Pointer & reference upcasting A crisis Demonstrates the need for polymorphism

Homework for ch. 14 Provided as separate handout (also available on our webpage --> agapie.net) Due Friday, Apr.27, at the beginning of class. Please hand in a hard-copy, do not email! EOL 4

The following slides cover more nitty-gritty rules on inheritance. These are provided FYI only, not for exam!