1 QUIZ Friends class Y; Is a forward declaration neeed here?
2 QUIZ Friends
3 QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They are not needed for global functions or entire structs/classes.
4 QUIZ Why is it sometimes not a good idea to place the private part of the interface in a header file?
5 Example projects where we don t want the implementation visible to the client programmer: The library header file may show proprietary info. that the company doesn t want available to competitors. Security (e.g. an encryption algorithm) don t want to expose any clues in a header file that might help people crack the code. Library is used in a hostile environment, where the programmers will try to directly access the private components anyway, using pointers and casting.
6 QUIZ Why can a.cpp file be made more secure than a header file?
7 QUIZ Why can a.cpp file be made more secure than a header file? Because it can be provided in the library in an already-compiled form, so the client programmers don t have access to the source code.
8 QUIZ What is the fragile base-class problem?
9 QUIZ The fragile base-class problem: Any time we make a change to a class (public interface or private member declarations), it is necessary to recompile all files that include that header file. For a large project in its early stages this can be very unwieldy because the underlying implementation may change often; if the project is very big, the time for compiles can prohibit rapid turnaround.
10 QUIZ What is a handle class?
11 QUIZ What is a handle class? A class that is accessed only through an opaque pointer; the class interface and definition are not available to the client programmer.
12 QUIZ How is a handle class implemented in C++?
13 QUIZ How is a handle class implemented in C++? With a forward declaration and a pointer:
14 Ch. 6: Initialization & Cleanup
15 Main ideas from chs. 4 and 5 Encapsulation (functions inside struct/class) Access control (hiding)
16 Two more safety issues: A large segment of C bugs occur when the programmer forgets to initialize or clean up a variable. This is especially true with C libraries, when client programmers don t know how to initialize a struct, or even that they must. (Libraries often do not include an initialization function, so the client programmer is forced to initialize the struct by hand.)
17 Two more safety issues: C programmers are comfortable with forgetting about variables once they are finished, so any cleaning up that may be necessary for a library s struct is often missed. What if we allocated memory dynamically for a large array? Memory leaks!
18 Guaranteed initialization with the constructor Both the Stash and Stack classes defined previously have a function called initialize( ), which hints by its name that it should be called before using the object in any other way. Unfortunately, this means the client programmer must ensure proper initialization by calling it.
19 Guaranteed initialization with the constructor In C++, initialization is too important to leave to the client programmer. The class designer can guarantee initialization of every object by providing a special function called the constructor. If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client programmers can get their hands on the object.
20 Note that the constructor is in the public section of the interface! Name of constructor is the same as name of class.
21 What happens if we make the constructor private?
22 It is still possible to create objects of this class, but we have to use other member functions in Test, of friend functions. Conclusion: The constructor should be public (unless we have a good reason to the contrary).
23 the same thing happens as if a were an int: storage is allocated for the object. But [unlike an int] when the program reaches the sequence point (point of execution) where a is defined, the constructor is called automatically. That is, the compiler quietly inserts the call to X::X( ) for the object a at the point of definition.
24 Like any member function, the first (secret) argument to the constructor is the this pointer the address of the object for which it is being called. In the case of the constructor, however, this is pointing to an un-initialized block of memory, and it s the job of the constructor to initialize this memory properly.
27 QUIZ 3. Modify Exercise 1 so that the class contains an int member. Modify the constructor so that it takes an int argument that it stores in the class member. The constructor should print out the int value as part of its message, so you can see the objects as they are created. Create 2 objects of this class, with different arguments passed to the constructor.
29 Both constructor and destructor are unusual functions: they have no return value. This is distinctly different from a void return value, in which the function returns nothing but you still have the option to make it something else.
30 [ ] the compiler always makes these function calls itself, to make sure they happen properly. If there were a return value, and if you could select your own, the compiler would somehow have to know what to do with the return value, or the client programmer would have to explicitly call constructors and destructors, which would eliminate their safety.
31 We stop before the section Guaranteed cleanup with the destructor EOL 17
32 QUIZ What (if anything) is wrong with this code?
33 QUIZ How are constructors different from regular member functions?
34 QUIZ How are constructors different from regular member functions? They have the same name as the class They have no return type They are called automatically when objects are declared
35 QUIZ Can C++ structs have constructors?
36 QUIZ Can C++ structs have constructors? Yes, remember that there s only one difference between structs and classes in C++!
37 Guaranteed cleanup with the destructor No return type No arguments! Tilde Same name as the class
38 The destructor is called automatically by the compiler when the object goes out of scope. You can see where the constructor gets called by the point of definition of the object, but the only evidence for a destructor call is the closing brace of the scope that surrounds the object.
39 ~Tree() is called here
43 QUIZ How are constructors and destructors: Similar? Different?
44 [ ] the destructor is still called, even when you use goto to jump out of a scope. (goto still exists in C++ for backward compatibility with C and for the times when it comes in handy.) You should note that a nonlocal goto, implemented by the Standard C library functions setjmp( ) and longjmp( ), doesn t cause destructors to be called.
45 Elimination of the definition block In C, you must always define all the variables at the beginning of a block, after the opening brace. [ ] it s good programming style. However: It has always seemed inconvenient to me to pop back to the beginning of a block every time I need a new variable. I find code more readable when the variable definition is close to its point of use.
46 Elimination of the definition block In C++, however, there s a significant problem in being forced to define all objects at the beginning of a scope: If a constructor exists, it must be called when the object is created. However, if the constructor takes one or more initialization arguments, how do you know you will have that initialization information at the beginning of a scope?
48 Doesn t matter whether we use braces or not the scope is always the body of the loop. (Of course, w/o braces, the body of the loop is only one command.)
49 QUIZ What will this code print?
51 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. I.e. have the same name as
52 I find small scopes an indicator of good design. If you have several pages for a single function, perhaps you re trying to do too much with that function. More granular functions are not only more useful, but they also make it easier to find bugs.
53 To make sure all objects are properly initialized, the compiler even checks to make sure that you don t put the object definition (and thus the constructor call) where the sequence point only conditionally passes through it, such as in a switch statement or somewhere a goto can jump past it.
55 Stash with constructors and destructors
57 Stack with constructors & destructors will be covered in the lab
58 Aggregate initialization An aggregate is just what it sounds like: a bunch of things clumped together. This definition includes aggregates of mixed types, like structs and classes. An array is an aggregate of a single type. Initializing aggregates can be error-prone and tedious. C++ aggregate initialization makes it much safer.
59 All these cases are identical to C:
60 All these cases are identical to C:
61 If any of the data members are private (which is typically the case for a well-designed class in C++), or even if everything s public but there s a constructor, things are different:
62 An example with constructors having multiple arguments:
63 Default constructors
65 You might think that the compiler-synthesized constructor should do some intelligent initialization, like setting all the memory for the object to zero. But it doesn t that would add extra overhead [ ] If you want the memory to be initialized to zero, you must do it yourself by writing the default constructor explicitly.
66 Another reason for lazy default constructors is that, in many cases, it is not clear what the default value should be for an object! E.g. How should be dates initialized?
67 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.
68 Ambiguity: In the next chapter we shall encounter overloaded constructors:
69 There is no homework for ch. 6 assigned today! One homework will be assigned for 6 and 7 together. EOL 18
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The
Friends We want to explicitly grant access to a function that isn t a member of the current class/struct. This is accomplished by declaring that function (or an entire other struct) as friend inside the
Ch. 10: Name Control Static elements from C The static keyword was overloaded in C before people knew what the term overload meant, and C++ has added yet another meaning. The underlying concept with all
QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of
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
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
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. Ch. 14: Inheritance
QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of
#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
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
G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And
A student was asked to point out interface elements in this code: Answer: cout. What is wrong? Clarification of the concept of INTERFACE The interface we ve been talking about in OOP is not the man-machine
Implementing Abstractions Pointers A pointer is a C++ variable that stores the address of an object. Given a pointer to an object, we can get back the original object. Can then read the object's value.
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
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
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 12: Classes and Data Abstraction Objectives In this chapter, you will: Learn about classes Learn about private, protected,
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the
10. Abstract Data Types 11.1 The Concept of Abstraction The concept of abstraction is fundamental in programming Nearly all programming languages support process abstraction with subprograms Nearly all
CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction
Exception Safe Coding Dirk Hutter email@example.com Prof. Dr. Volker Lindenstruth FIAS Frankfurt Institute for Advanced Studies Goethe-Universität Frankfurt am Main, Germany http://compeng.uni-frankfurt.de
Chapter 10 :: Data Abstraction and Object Orientation Programming Language Pragmatics, Fourth Edition Michael L. Scott Copyright 2016 Elsevier Chapter10_Data_Abstraction_and_Object_Orientation_4e 1 Object-Oriented
C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this
Programming Style and Optimisations - An Overview Summary In this lesson we introduce some of the style and optimization features you may find useful to understand as a C++ Programmer. Note however this
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
Basic Class Design Goal of OOP: Reduce complexity of software development by keeping details, and especially changes to details, from spreading throughout the entire program. Actually, the same goal as
C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
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 loops Ch 3.3-3.4 Announcements Quiz next week! -Covers up to (and including) HW1 (week 1-3) -Topics: cout/cin, types, scope, if/else, etc. Review: Loops We put a loop around code that we want to run
Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output
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
OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
Programming in C and C++ 5. C++: Overloading, Namespaces, and Classes Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford
Chapter 11 Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept
CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,
Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will
CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
CS11 Introduction to C++ Fall 2006-2007 Lecture 6 Today s Topics C++ exceptions Introduction to templates How To Report Errors? C style of error reporting: return values For C Standard Library/UNIX functions,
Doc No: SC22/WG21/ N1742=04-0182 Project: Programming Language C++ Date: Sunday, November 07, 2004 Author: Francis Glassborow email: firstname.lastname@example.org Auxiliary class interfaces (This is a replacement
CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG 1 Notice Prepare the Weekly Quiz The weekly quiz is for the knowledge we learned in the previous week (both the
CIT Intro to Computer Systems Lecture # (//) Functions As you probably know from your other programming courses, a key part of any modern programming language is the ability to create separate functions
Makefile Tutorial Eric S. Missimer December 6, 2013 1 Basic Elements of a Makefile 1.1 Explicit Rules A the major part of a Makefile are the explicit rules (a.k.a. recipes) that make certain files. Below
CMSC162 Intro to Algorithmic Design II Blaheta Lab 10 28 March 2019 This week we ll take a brief break from the Set library and revisit a class we saw way back in Lab 4: Card, representing playing cards.
04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here
Chapter 9 :: Data Abstraction and Object Orientation Programming Language Pragmatics Michael L. Scott Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it in
1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity
Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively
Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public
Chapter 13: Copy Control Overview The Copy Constructor The Assignment Operator The Destructor A Message-Handling Example Managing Pointer Members Each type, whether a built-in or class type, defines the
C++ Style Guide 1.0 General The purpose of the style guide is not to restrict your programming, but rather to establish a consistent format for your programs. This will help you debug and maintain your
More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors
Pointers, Arrays and Parameters This exercise is different from our usual exercises. You don t have so much a problem to solve by creating a program but rather some things to understand about the programming
An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
Classes and Objects So far you have explored the structure of a simple program that starts execution at main() and enables you to declare local and global variables and constants and branch your execution
OBJECT ORIENTED PROGRAMMING USING C++ Abstract Data Types and Encapsulation Concepts ISBN 0-321-33025-0 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract
Chapter 3: Functions 3.1 Introduction The previous chapter assumed that all of your Bali code would be written inside a sole main function. But, as you have learned from previous programming courses, modularizing
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 C Pointers 2004-09-08 Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Cal flies over Air Force We re ranked 13 th in the US and
Class #10: Understanding Primitives and Assignments Software Design I (CS 120): M. Allen, 19 Sep. 18 Java Arithmetic } Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = 2 + 5 / 2; 3.
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
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2015 Lecture 11 EXCEPTION HANDLING! Many higher-level languages provide exception handling! Concept: One part of the program knows how to detect a problem,
Templates Templates are functions or classes that are parameterized. We have already seen a few in STL: std::vector< int > std::vector< double > std::list< std::vector< >> std::unordered_map< int, bool
A l l e n I. H o l u b & A s s o c i a t e s Home C/C++ and OO Rules of Thumb The following list is essentially the table of contents for my book Enough Rope to Shoot Yourself in the Foot (McGraw-Hill,
1 CS 242 History C++ John Mitchell C++ is an object-oriented extension of C C was designed by Dennis Ritchie at Bell Labs used to write Unix based on BCPL C++ designed by Bjarne Stroustrup at Bell Labs
Lecturer: William W.Y. Hsu Programming Languages Chapter 9 Data Abstraction and Object Orientation 3 Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though