QUIZ. Can you find 5 errors in this code?

Similar documents
QUIZ Friends class Y;

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

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

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

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

QUIZ. Source:

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?

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

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

QUIZ. How could we disable the automatic creation of copyconstructors

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

Ch. 10: Name Control

Ch. 12: Operator Overloading

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

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

Object Oriented Design

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ with content from

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

CSE 333 Midterm Exam Sample Solution 5/10/13

Lesson 7. Reading and Writing a.k.a. Input and Output

CMSC 330: Organization of Programming Languages

10. Abstract Data Types

Instantiation of Template class

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

CSE 333 Midterm Exam 5/10/13

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

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

Programming in C and C++

Lecture 16: Static Semantics Overview 1

Week 8: Operator overloading

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

C++ for Java Programmers

Chapter 1 Getting Started

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

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

CS201 Latest Solved MCQs

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Object Oriented Design

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

BLM2031 Structured Programming. Zeyneb KURT

Final CSE 131B Spring 2004

Introduction to Programming Using Java (98-388)

EL6483: Brief Overview of C Programming Language

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

First of all, it is a variable, just like other variables you studied

C-LANGUAGE CURRICULAM

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe


Pointers (continued), arrays and strings

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

CSCI312 Principles of Programming Languages!

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

Pointers (continued), arrays and strings

Fast Introduction to Object Oriented Programming and C++

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

The New C Standard (Excerpted material)

Type Checking and Type Equality

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Lecture Topics. Administrivia

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Intermediate Programming, Spring 2017*

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

22c:111 Programming Language Concepts. Fall Types I

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

A Fast Review of C Essentials Part II

Computer Science 306 Study Guide

Data Types (cont.) Administrative Issues. Academic Dishonesty. How do we detect plagiarism? Strongly Typed Languages. Type System

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Pointers, Arrays and Parameters

An Object Oriented Programming with C

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Names, Scope, and Bindings

OBJECT ORIENTED PROGRAMMING USING C++

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

A brief introduction to C programming for Java programmers

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

For Teacher's Use Only Q No Total Q No Q No

Procedure and Object- Oriented Abstraction

Review of the C Programming Language

CSE 374 Programming Concepts & Tools

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Lectures 5-6: Introduction to C

Lecture 18 Tao Wang 1

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

QUIZ: What value is stored in a after this

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

Transcription:

QUIZ Can you find 5 errors in this code?

QUIZ What (if anything) is wrong with this code? public: ; int Constructor argument need!

QUIZ What is meant by saying that a variable hides another?

I.e. have the same name as Watch out for local variables that hide variables from the enclosing scope. In general, using the same name for a nested variable and a variable that is global to that scope is confusing and error-prone.

QUIZ Only one of these programs compiles successfully which one and why?

QUIZ Only one of these programs compiles successfully which one and why?

QUIZ Will the program compile now? Why?

Solution Yes, b/c if the class has no constructors, the compiler will create (synthesize) a default one. What is the first rule about using default constructors?

Although the compiler will create a default constructor for you, the behavior of the compilersynthesized constructor is rarely what you want. You should treat this feature as a safety net, but use it sparingly. In general, you should define your constructors explicitly and not allow the compiler to do it for you.

Ch. 7: Function Overloading & Default Arguments

Most [procedural] programming languages require that you have a unique identifier for each function. If you have three different types of data that you want to print: int, char, and float, you generally have to create three different function names, for example, print_int( ), print_char( ), and print_float( ). This loads extra work on you as you write the program, and on readers as they try to understand it.

In C++, another factor forces the overloading of function names: the constructor. Because the constructor s name is predetermined by the name of the class, it would seem that there can be only one constructor. But what if you want to create an object in more than one way?

For example, suppose you build a class that can initialize itself in a standard way and also by reading information from a file. You need two constructors, one that takes no arguments (the default constructor) and one that takes a string as an argument, which is the name of the file to initialize the object. Both are constructors, so they must have the same name: the name of the class. Overloading example

Definitions on next slide

User code on next slide

More name decoration

More name decoration

More name decoration There is no standard for the way names must be decorated by the compiler, so you will see very different results from one compiler to another. example

This is what I found in the assembly code generated by MSVS 2010:

Overloading on return values? This works fine when the compiler can unequivocally determine the meaning from the context, as in int x = f( );

However, in C you ve always been able to call a function and ignore the return value (that is, you can call the function for its side effects). In this example, we re using getchar only to stop the program execution, but we re not interested in the actual key that was pressed.

If there were overloaded versions of the function that differed only in the return value, how could the compiler distinguish which call is meant in this case?

Possibly worse is the difficulty the reader has in knowing which function call is meant. Overloading solely on return value is a bit too subtle, and thus isn t allowed in C++.

Languages that do not allow overloading only on return values C++, Java, C# Languages that do allow overloading only on return values Haskell, ADA, Perl

Type-safe linkage In one file is the definition for a function. In the second file, the function is redeclared (misdeclared!) and then called. The compilation is successful, b/c each file is compiled separately.

In C, the linker would also be successful, but not in C++. Because the compiler decorates the names, the definition becomes something like f_int, whereas the use of the function is f_char. When the linker tries to resolve the reference to f_char, it can only find f_int, and it gives you an error message. This is type-safe linkage.

The section unions was assigned for reading in Ch.3

How to misuse unions:

QUIZ C/C++ unions and enumerations Write a global function assign_char() that creates and returns a Node with data of type char. Use it in a main program.

Solution

Back to Ch.7: unions in C++ Just like struct and class, a union can also have a constructor, destructor, member functions, and even access control. (However, a union cannot be used as a base class during inheritance.)

Initializing a union is simplified with constructors (no more manual decoration!)

Would X.read_float() work here?

To make union operations safer, we store the type alongside the data (this was already possible in C)

And now we can print safely like this

We stop before the section unions Individual work for next time: End-of-chapter 1, 3. Review Unions and Enumerations from Ch.3 EOL 1

What is type-safe linkage? QUIZ

QUIZ What is type-safe linkage? Type-safe linkage enforces that function declarations and definitions must have the same number and types of arguments at link-time.

QUIZ Can C++ functions be overloaded solely on return values? Explain, either way.

QUIZ What is meant by calling a function only for its side-effects?

Example: putchar() putchar() details

Extra-credit

Extra-credit#2

Default arguments A default argument is one the compiler inserts if it isn t specified in the function call. Thus, the calls f( hello ) ; f( hi, 1) ; f( howdy, 2, c ) ; can all be calls to the same function. They could also be calls to three overloaded functions (if the overloaded functions have been defined).

Remember the two constructors for stash?

They can be replaced with only one! Only trailing arguments may be defaulted. That is, you can t have a default argument followed by a nondefault argument. The value of the default argument ( = 0) can be placed either in the declaration or the definition, but not in both!

QUIZ Write the prototype (declaration) of a function person with three arguments, an integer and two strings. The strings can default to John and Snow, respectively.

READ: Placeholder arguments

Choosing overloading vs. default arguments Code from text

Make sure you re including the current name of the header file!

Code walk-though...

Answer the following questions about the code:

Isn t it inefficient to delete the old memory block? Why do we allocate a new block instead of just enlarging the existing block? What is the purpose of memset()? Explain newmem + size

What would happen if we forgot delete []mem; Explain in your own words what this function does.

What would happen if we wrote a simpler memset like this: memset(newmem, 0, minsize); Would the code still work correctly?

It s still correct, although inefficient: extra time is spent filling with zeroes the first size bytes, which are then copied from the old block. What would happen if we wrote a simpler memset like this: memset(newmem, 0, minsize); Would the code still work correctly?

Based on our understanding of ensureminsize(), explain the difference between the two overloaded versions of pointer().

Explain the operation of the C functions strlen() and strcpy(). Explain the +1. Explain (char *)buf->pointer(). precedence? See next slide.) (Hint: What is the Is it OK to use the default constructor above, or should the other version be used: pointer(int minsize)? Precedence table on next slide

Let s take a closer look at how the two overloaded constructors are being used: What is the difference in terms of efficiency?

Replace the two overloaded constructors with one, having a default argument Hint: Make sure the code still works!

Replace the two overloaded constructors with one, having a default argument

What is the difference NOW in terms of efficiency?

What is the difference NOW in terms of efficiency? A: Efficiency of default constructor is lost, since both calls now create the new object and call strcpy().

Text has default argument in prototype We can restore the efficiency by using the default value as a flag to decide which code to call at a small price Can you see what the price is?

Text has lost the default argument Can you see what the price is? A: We re always passing a parameter, and always executing an if statement.

Text has lost the default argument More important considerations are code clarity and maintainability; because of this, it is recommended to keep the original overloaded functions!

Can we draw the same conclusion for this pair of overloaded constructors? Declarations Definitions

Can we draw the same conclusion for this pair of overloaded constructors? Declarations Definitions

Can we draw the same conclusion for this pair of overloaded constructors? Write the unique constructor with default argument

Can we draw the same conclusion for this pair of overloaded constructors? Look up the definitions and answer the question! Declarations

Can we draw the same conclusion for this pair of overloaded constructors? Declarations Definitions Look up the definitions and answer the question!

Can we draw the same conclusion for this pair of overloaded constructors? Write the unique constructor with default argument

Individual work for next time: End-of-chapter 1, 4, 5. Homework for chs. 6+7 Provided as separate handout (also available on our webpage --> agapie.net) Due Wednesday, Mar.21, at the beginning of class. Please hand in a hard-copy, do not email! EOL 2