Classes, Constructors, etc., in C++

Size: px
Start display at page:

Download "Classes, Constructors, etc., in C++"

Transcription

1 Classes, Constructors, etc., in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

2 Review struct A class in C++ in which all members are by default public Stylistically, may be used like structs in C. class Definition of a new type of data structure, including member functions and member data Similar to Java Definitions Member: one of the data items or functions declared within the body of a class Field or method in Java Object: an instance of a class, occupies memory, data values are populated in the instance 2

3 Recommended class structure for PA4 class TreeNode Defines the nodes of the binary tree Constructor, destructor Methods for accessing fields, updating links, comparing strings, incrementing counts class BinaryTree Includes a root pointing to a TreeNode Methods for inserting data, traversing and outputting data 3

4 TreeNode class TreeNode { public: int incr(); int getcount(); string getword(); int compare(const string &w2); TreeNode *setleft(treenode *t); TreeNode *setright(treenode *t); TreeNode *getleft(); TreeNode *getright(); // non-default constructor TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode 4

5 BinaryTree class BinaryTree{ public: TreeNode *AddNode(const string &word); int gettotalnodes(); void PrintTree(ostream &output); BinaryTree(); //Default constructor ~BinaryTree(); //Destructor private: Overloaded functions static int totalnodes; void PrintTree(TreeNode *subtree, ostream &output); TreeNode *AddNode(TreeNode *subtree, const string &word); TreeNode *root; }; // class BinaryTree 5

6 Note on Overloaded Functions A function may share a name with other functions but have different parameter list! E.g., AddNode() and PrintTree() in BinaryTree class E.g., sqrt() applied to double or complex When compiler detects overloading, it mangles the names of the functions AddNode(const string &word) AddNode_$string AddNode(TreeNode *subtree, const string &word) AddNode_$$subtree_$string thereby making them functions with different names! 6

7 Questions? 7

8 C++ Program Structure Typical C++ Programs consist of: A function main() One or more class definitions Each defining data members and member functions One of more class implementations Optionally: One or more static objects One or more non-member functions 8

9 Stylistic guidance Each class definition should have its own.h file Separate from all other class definitions Each class should have its own implementation in one or more.cpp files Separate from all other class implementations Plus one or more additional.cpp files For main(), etc. Required for this course! 9

10 Interfaces versus Implementation Interface Describes what services a class s clients can use and how to request those services. without revealing how the class carries out the services. a class definition listing only public member function prototypes. A class s interface consists of the class s public member functions (services). Defined in class header file (.h) 10

11 Interfaces vs.implementation Implementation of member functions In a separate source-code file for a class Use binary scope resolution operator (::) to tie each member function to the class definition. Implementation details are hidden. Client code does not need to know the implementation. 11

12 Example TreeNode interface /* * TreeNode.h */ #include <string> class TreeNode { public: int incr(); int getcount(); // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 12

13 Example TreeNode implementation /* * TreeNode.cpp */ #include "TreeNode.h" int TreeNode::incr(){ return ++count; } // int TreeNode::incr() int TreeNode::getCount(){ return count; } // int TreeNode::getCount() Scope Resolution operator :: TreeNode::~TreeNode{ delete left; delete right; delete word; } // TreeNode::~TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 13

14 Stylistic guidance Each class definition should have its own.h file Separate from all other class definitions Each class should have its own implementation in one or more.cpp files Separate from all other class implementations Plus one or more additional.cpp files For main(), etc. For reusability! 14

15 Software Engineering Observation As a rule of thumb, data members should be declared private Member functions should be declared public Except member functions that are accessed only by other member functions of the class. Often useful to have get() and set() member functions To access private members in controlled ways 15

16 Namespace A logical grouping of names to set them apart from other names to avoid conflicts among similar names See 8.2 Each class is its own namespace Other namespaces can be defined

17 Scope Resolution Operator int TreeNode::incr() int TreeNode::getCount() TreeNode::TreeNode(const string &w); The methods named incr(), getcount() and TreeNode() defined in the class TreeNode std::cout The object cout that is declared in namespace std 17

18 Using Directive Make one or more names from a namespace available in current scope Without specifying scope resolution operator each time E.g., using std::cout; using std::cin; using std::endl; These names may now be used in current scope without qualification 18

19 Common C++ Programming Error Forgetting to say using You get undeclared identifiers Even though you include the appropriate header file! Using std i.e., naked Bad style Makes all names in namespace std visible whether you need them or not! 19

20 Questions? 20

21 Constructors and Destructors Constructor: a member function used to initialize the data of an object of a class Same name as class itself Cannot return anything, not even void A class may define more than one constructor With different parameter lists Default constructor has no parameters Called automatically When class object is declared as an automatic or static variable By new operator Compiler s default simply calls constructors of data members of the class. Compiler provides one if you do not! For each element in a new array! 21

22 Constructors and Destructors (continued) Destructor: a function used to clean up an object of a class prior to deleting that object Class name preceeded by '~' No parameters, no result Compiler provides one if you do not! Called automatically When function exits scope of automatic class object By delete or delete[] operator Compiler s default simply calls destructors of data members of the class. delete[] cleans up each element of array 22

23 Constructors and Destructors (continued) Constructors Similar to Java Destructors No counterpart in Java Purpose of Destructors Free dynamic storage pointed to only by members of object Reduce reference count when object disappears Safely close things e.g., files 23

24 Constructor Example /* * TreeNode.h */ #include <string> /* * TreeNode.cpp */ #include "TreeNode.h // other methods TreeNode::TreeNode(const string &w){... } class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 24

25 What Must Constructor Do? (Allocate memory for whole object) Done before constructor method is called Initialize left, right members To zero (i.e., NULL) Initialize count member To 1 Create a string object word and initialize How? 25

26 Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 26

27 Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); string class supports '=' operator (Does the right thing!) private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 27

28 Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } Another problem /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 28

29 Constructor Example (continued) Member word is const may not be on left any assignment! Not even in constructors /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 29

30 Solution Initializer List A list of member-value pairs Or member-constructor pairs Between the () of the constructor header and the {} of the constructor body Preceded by ':' and separated by ',' 30

31 Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newword), //initialize word count(1), //initialize count left(0), //initialize left right(0) { /* rest of constructor body */ } // TreeNode constructor /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; CS-2303, A-Term 2012 }; // class TreeNode Widely used in the design of C++ classes Classes, Constructors, etc. 31

32 When are Constructors Called? Global Scope I.e., objects declared outside of any function Before main() is called! Function or Block Scope I.e., automatic variables and constants When execution reaches point where object is declared For static objects, the first time execution reaches point where object is declared Class Scope I.e., data members of a class When class constructor executes initialization list (or enters block scope of constructor function) Dynamic objects I.e., objects created by new Constructor is invoked by new operator 32

33 Common Programming Error Not providing a member initializer for a const data member is a compilation error. 33

34 Common Programming Error A compilation error occurs if a member object is not initialized with a member initializer and the member object s class does not provide a default constructor Even if member object s class defines one or more constructors, but none is a default constructor! 34

35 Questions? 35

36 Destructors The opposite of constructors Called to clean up objects before deleting them Very important if your class has members that are objects of other classes E.g., string Dynamically allocates array of characters to hold the string itself Must be freed before string object can be deleted 36

37 Destructor Example /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newword), //initialize word count(1), //initialize count left(0), //initialize left right(0) { } // TreeNode constructor TreeNode::~TreeNode() { if (left) delete left; if (right) delete right; left = right = 0; } // TreeNode destructor /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 37

38 Destructor Example /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newword), //initialize word count(1), //initialize count left(0), //initialize left right(0) { } // TreeNode constructor TreeNode::~TreeNode() { if (left) delete left; if (right) delete right; left = right = 0; } // TreeNode destructor /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods Worcester Polytechnic Carnegie Institute Mellon Note: destructor for string word and for count are called automatically (because these are in class scope). Destructors for left and right have to be called forcibly, because those object were allocated dynamically TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 38

39 When are Destructors Called? In opposite order of constructors (mostly) Dynamic objects Invoked by delete operator Class scope I.e., data members of a class Invoked by destructor of class object Function or Block Scope When just before leaving the scope Global Scope After main() has returned 39

40 Exceptions to calling destructors static objects in function or block scope After main() has returned but before calling destructors of objects in Global Scope exit() function Destructors of automatic objects are not called Usually means abnormal termination of program, file cannot be opened, etc. abort() function No destructors are called Usually means serious error, etc. 40

41 Dynamically Allocated Objects Always use new operator (as in Java) Returns pointer to object (as with malloc() in C) Never use malloc() There is a lot more to creating an object in C++ than simply allocating memory new calls malloc() to allocate memory, calls constructor, sets up inheritance, finds the right polymorphic functions, etc. Always use delete or delete[] operator Invokes destructor, cleans up, calls free(), etc. Takes pointer to object Never call free() directly For same reasons not to call malloc(); memory leaks, etc. 41

42 Constructor-Destructor Summary Constructors are a big deal A class may have many constructors Different parameter lists Destructors are a bigger deal Class only has one destructor Must tidy up everything after itself Include delete of member objects 42

43 Questions? 43

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts Iterators Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch,

More information

Programming Assignment #4 Binary Trees in C++

Programming Assignment #4 Binary Trees in C++ Programming Assignment #4 Binary Trees in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie,

More information

Containers and the Standard Template Library (STL)

Containers and the Standard Template Library (STL) Containers and the Standard Template Library (STL) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Derived Classes in C++

Derived Classes in C++ Derived Classes in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Linked Lists in C and C++

Linked Lists in C and C++ Linked Lists in C and C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

Your first C and C++ programs

Your first C and C++ programs Your first C and C++ programs Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++,

More information

Exception Handling in C++

Exception Handling in C++ Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan

More information

Binary Trees (and Big O notation)

Binary Trees (and Big O notation) Binary Trees (and Big O notation) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development 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

More information

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

And Even More and More C++ Fundamentals of Computer Science 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

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ 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

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 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)

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

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

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

Structures, Unions, and Typedefs

Structures, Unions, and Typedefs Structures, Unions, and Typedefs Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (ramviyas@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Classes (cont d) More on Classes and Members Group presentations Last time

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

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

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

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

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 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

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch,

More information

ECE 244 Programming Fundamentals Fall Lab Assignment #5: Binary Search Trees

ECE 244 Programming Fundamentals Fall Lab Assignment #5: Binary Search Trees ECE 244 Programming Fundamentals Fall 2012 1. Objectives Lab Assignment #5: Binary Search Trees The objectives of this assignment are to provide you with more practice on the use of the various C++ concepts/constructs

More information

An Introduction to C++

An Introduction to C++ 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

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

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

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

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

CS201 Some Important Definitions

CS201 Some Important Definitions 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

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez! C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a

More information

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370 Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip

More information

Programming in C and C++

Programming in C and C++ 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

More information

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; } Multiple choice questions, 2 point each: 1. What output is produced by the following program? #include int f (int a, int &b) a = b + 1; b = 2 * b; return a + b; int main( ) int x=1, y=2, z=3;

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Arrays and Pointers in C & C++

Arrays and Pointers in C & C++ Arrays and Pointers in C & C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++,

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Tree Travsersals and BST Iterators

Tree Travsersals and BST Iterators Tree Travsersals and BST Iterators PIC 10B May 25, 2016 PIC 10B Tree Travsersals and BST Iterators May 25, 2016 1 / 17 Overview of Lecture 1 Sorting a BST 2 In-Order Travsersal 3 Pre-Order Traversal 4

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure you review all previous exams and make sure you fully understand

More information

PHY4321 Summary Notes

PHY4321 Summary Notes PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t

More information

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez! C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a

More information

Exam Informatik D-MATH/D-PHYS :00 11:00

Exam Informatik D-MATH/D-PHYS :00 11:00 Exam Informatik D-MATH/D-PHYS 25. 1. 2013 09:00 11:00 Dr. Bernd Gartner Examinee: Last name:... First name:... Stud. no.:... With my signature I attest, that I was able to sit the exam under regular conditions

More information

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

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes C++ C and C++ 5. Overloading Namespaces Classes Alastair R. Beresford University of Cambridge Lent Term 2007 To quote Bjarne Stroustrup: C++ is a general-purpose programming language with a bias towards

More information

Interview Questions of C++

Interview Questions of C++ 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.

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

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

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Final Examination 8:30 AM, Wednesday, April 18, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Final Examination 8:30 AM, Wednesday, April 18, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Final Examination 8:30 AM, Wednesday, April 18, 2012 Instructor: K. S. Booth Time: 150 minutes (two hours thirty minutes)

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Run Time Environment

Run Time Environment CS 403 Compiler Construction Lecture 12 Run Time Environment and Management [Based on Chapter 7 of Aho2] 1 Run Time Environment From Lecture 1 to 11, we have seen many jobs that are done by a compiler.

More information

lecture14: Tree Traversals

lecture14: Tree Traversals lecture14: Tree Largely based on slides by Cinda Heeren CS 225 UIUC 2nd July, 2013 Announcements lab trees due Saturday night (7/6) Reminder: no class 7/4 mp4.1 extra credit due Friday night (7/5) Source:

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CS 11 C++ track: lecture 1

CS 11 C++ track: lecture 1 CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/

More information

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

G52CPP C++ Programming Lecture 14. Dr Jason Atkin G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used

More information

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

More information

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli COMS W3101 Programming Language: C++ (Fall 2016) ramana@cs.columbia.edu Lecture-2 Overview of C C++ Functions Structures Pointers Design, difference with C Concepts of Object oriented Programming Concept

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

CS 241 Data Organization Binary Trees

CS 241 Data Organization Binary Trees CS 241 Data Organization Binary Trees Brooke Chenoweth University of New Mexico Fall 2017 Binary Tree: Kernighan and Ritchie 6.5 Read a file and count the occurrences of each word. now is the time for

More information

This examination has 11 pages. Check that you have a complete paper.

This examination has 11 pages. Check that you have a complete paper. MARKING KEY The University of British Columbia MARKING KEY Computer Science 252 2nd Midterm Exam 6:30 PM, Monday, November 8, 2004 Instructors: K. Booth & N. Hutchinson Time: 90 minutes Total marks: 90

More information

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS93SI Handout 04 Spring 2006 Apr Review Answers CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2009 7p-9p, Tuesday, Feb 24 Name: NetID: Lab Section (Day/Time):

More information

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes

More information

Set Implementation Version 1

Set Implementation Version 1 Introduction to System Programming 234122 Set Implementation Version 1 Masha Nikolski, CS Department, Technion 1 // Version 1.0 2 // Header file for set class. 3 // In this implementation set is a container

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts

Chapter 11. Abstract Data Types and Encapsulation Concepts 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

More information

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each). A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

CMSC 341 Lecture 10 Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees CMSC 341 Lecture 10 Binary Search Trees John Park Based on slides from previous iterations of this course Review: Tree Traversals 2 Traversal Preorder, Inorder, Postorder H X M A K B E N Y L G W UMBC CMSC

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University (5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming

More information

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related

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

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

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Section 1 Multiple Choice Questions (40 pts total, 2 pts each): Q1: Employee is a base class and HourlyWorker is a derived class, with

More information

C++ 8. Constructors and Destructors

C++ 8. Constructors and Destructors 8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory

More information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 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

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 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

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

COIMBATORE EDUCATIONAL DISTRICT

COIMBATORE EDUCATIONAL DISTRICT COIMBATORE EDUCATIONAL DISTRICT REVISION EXAMINATION JANUARY 2015 STD-12 COMPUTER SCIENCE ANSEWR KEY PART-I Choose the Correct Answer QNo Answer QNo Answer 1 B Absolute Cell Addressing 39 C Void 2 D

More information

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

selectors, methodsinsert() andto_string() the depth of a tree and a membership function Binary Search Trees 1 Sorting Numbers using a Tree a sorting algorithm using a tree of integer numbers 2 Header Files defining a node struct defining a tree class 3 Definition of Methods selectors, methodsinsert()

More information

Crash Course into. Prof. Dr. Renato Pajarola

Crash Course into. Prof. Dr. Renato Pajarola Crash Course into Prof. Dr. Renato Pajarola These slides may not be copied or distributed without explicit permission by all original copyright holders C Language Low-level programming language General

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Example Final Questions Instructions

Example Final Questions Instructions Example Final Questions Instructions This exam paper contains a set of sample final exam questions. It is for practice purposes only. You ll most likely need longer than three hours to answer all the questions.

More information

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information