Quick Introduction to C++

Similar documents
Object Oriented Software Design II

C++ INTERVIEW QUESTIONS

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The C Programming Language course syllabus associate level

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

C++ Programming Language

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Curriculum Map. Discipline: Computer Science Course: C++

13 Classes & Objects with Constructors/Destructors

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

An Incomplete C++ Primer. University of Wyoming MA 5310

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Glossary of Object Oriented Terms

Chapter 5 Names, Bindings, Type Checking, and Scopes

Applied Informatics C++ Coding Style Guide

Moving from CS 61A Scheme to CS 61B Java

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

C++ Overloading, Constructors, Assignment operator

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

El Dorado Union High School District Educational Services

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Member Functions of the istream Class

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

A deeper look at Inline functions

C++FA 5.1 PRACTICE MID-TERM EXAM

Data Structures Using C++ 2E. Chapter 5 Linked Lists

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

Sources: On the Web: Slides will be available on:

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

Lecture 9. Semantic Analysis Scoping and Symbol Table

Evolution of the Major Programming Languages

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Introduction to Data Structures

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Semantic Analysis: Types and Type Checking

Conversion Constructors

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Parameter passing in LISP

Lecture 22: C Programming 4 Embedded Systems

Classes and Pointers: Some Peculiarities (cont d.)

CEC225 COURSE COMPACT

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

The programming language C. sws1 1

CS 241 Data Organization Coding Standards

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Java Interview Questions and Answers

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Programming Languages

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Basics of I/O Streams and File I/O

Code Refactoring and Defects

Compiler Construction

Common Data Structures

ECS 165B: Database System Implementa6on Lecture 2

Introduction to Scientific Computing Part II: C and C++ C. David Sherrill School of Chemistry and Biochemistry Georgia Institute of Technology

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

6.S096 Lecture 1 Introduction to C

Syllabus OBJECT ORIENTED PROGRAMMING C++

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Basics of C++ and object orientation in OpenFOAM

Class Notes for CSCI 104: Data Structures and Object-Oriented Design

1. Polymorphism in C++...2

Course notes Standard C++ programming

Description of Class Mutation Mutation Operators for Java

C and C++: Case Studies in Compatibility

Brent A. Perdue. July 15, 2009

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Stacks. Linear data structures

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Illustration 1: Diagram of program function and data flow

Advanced Data Structures

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

CS 111 Classes I 1. Software Organization View to this point:

Variable Base Interface

C++FA 3.1 OPTIMIZING C++

Object Oriented Software Design II

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Limitations of Data Encapsulation and Abstract Data Types

COMPARISON OF OBJECT-ORIENTED AND PROCEDURE-BASED COMPUTER LANGUAGES: CASE STUDY OF C++ PROGRAMMING

Top 10 Bug-Killing Coding Standard Rules

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Application of Stacks: Postfix Expressions Calculator (cont d.)

Chapter 7: Additional Topics

Functions and Parameter Passing

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Course Title: Software Development

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Quotes from Object-Oriented Software Construction

CS193j, Stanford Handout #4. Java 2

Transcription:

Quick Introduction to C++ Wayne A. Christopher handout for CS 162, UC Berkeley, 1992 (freely adapted by Riccardo Bettati ) C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you do, it blows away your whole leg. Bjarne Stroustrup The CPSC 410 project is written in a subset of C++, and you will be expected to understand and modify this code. Since you have already used C in previous classes, we hope that it will be easy for you to make the change to C++, if you have not done so. We tried to make the code as readable as possible, so you should look over it as you read this introduction. You should not need to buy a book for C++ for this class, but if you are curious or expect to use the language more in the future, there is a large selection at the local bookstores. Be sure to get one that describes Version 2.0 of the language. The ultimate reference is probably The C++ Programming Language by Bjarne Stroustrup, the author of C++. As typical for programming language books written by the language authors, it is rather terse to read. Other books may be more readable if you have opinions, please share. To a large extent, C++ is a superset of C, and most carefully written ANSI C will compile as C++. There are a few major caveats though, which may or may not come up in the code you will write: All functions must be declared before they are used, rather than defaulting to type int. All function declarations and definition headers must use new-style declarations, e.g., extern int foo(int a, char* b); The form extern int foo(); means that foo takes no arguments, rather than arguments of an unspecified type and number. If you need to link C object files together with C++, when you declare the C functions for the C++ files, they must be done like extern "C" int foo(int a, char* b); Otherwise the C++ compiler will alter the name in a strange manner. There are a number of new keywords, which you may not use as identifiers some common ones are new, delete, const, and class. 1 Basic Concepts Before giving examples of C++ features, we will first go over some of the basic concepts of object-oriented languages. If this discussion seems a bit obscure, it will become clearer once we have some concrete examples to talk about. 1. Classes and objects. A class defines a set of objects, or instances of that class. One declares a class in a way similar to a C structure, and then creates objects of that class. A class defines two aspects of the objects: the data they contain, and the behavior they have. Not without help from R.Sethi, Programming Languages: Concepts and Constructs, Addison-Wesley, 1989 1

2. Member functions. These are functions that are considered part of the object and are declared in the class definition. They are often referred to as methods of the class. In addition to member functions, a class s behavior is also defined by: (a) What to do when you create a new object (the constructor for that object). (b) What to do when you delete an object (the destructor for that object). 3. Private, public, and protected members. A public member of a class is one that can be read or written by anybody, in the case of a data member, or called by anybody, in the case of a member function. A private member can only be read, written, or called by a member function of that class. Classes may also have protected members, which can only be read, written, or called by a member function of that class, or a member function of a derived class (we will talk about this in the section on inheritance). Classes are used for two main reasons: (1) it makes it much easier to organize your programs if you can group together data with the functions that manipulate that data, and (2) the use of private members makes it possible to do information hiding, so that you can be more confident about the way information flows in your programs (if you want to impress people, you call this enforcing invariants). 2 Classes C++ classes are similar to C structures in many ways. In fact, a C struct is really a class in which all members are public. In the following explanation of how classes work, we will use a stack class as an example. 2.0.1 Member Functions Here is a (partial) example of a class with a member function and some data members: int top; // Index of the top of the stack. int stack[10]; // The elements of the stack. ; void Stack::Push(int value) { if (top == 10) { fprintf(stderr, "Error: exit(1); stack[top++] = value; Stack overflow"); This class has two data members, top and stack, and one member function, Push. The notation class::function denotes the function member of the class class. The function is defined beneath it. In actual usage, the definition of class Stack would typically go in the file stack.h and the definitions of the member functions, like Stack::Push, would go in the file stack.c. If we have a pointer to a Stack object called s, we can access the top element as s->top, just as in C. However, in C++ we can also call the member function using the following syntax: s->push(17); Of course, as in C, s must point to a valid Stack object. Inside a member function, one may refer to the members of the class by their names alone. In other words, the class definition creates a scope that includes the member function definitions. 2

Note that if you are inside a member function, you can get a pointer to the object you were called on by using the variable this. If you want to call another member function on the same object, you do not need to use the this pointer, however. Let s extend the Stack example to illustrate this by adding a Full() function. int top; // Index of the top of the stack. int stack[10]; // The elements of the stack. ; int Stack::Full() { return (top == 10); Now we can rewrite Push in the following way: void Stack::Push(int value) { if (Full()) { fprintf(stderr, "Error: exit(1); stack[top++] = value; Stack overflow"); We could have written the line with Full() this way also: if (this->full()) { but in a member function, the this-> is implicit. The purpose of member functions is to encapsulate the functionality of a type of object along with the data that the object contains. A member function does not take up space in an object of the class. 2.0.2 Private Members One can declare some members of a class to be private, which are hidden to all but the member functions of that class, and some to be public, which are visible and accessible to everybody. Both data and function members can be either public or private. In our stack example, note that once we have the Full() function, we really don t need to look at the top or stack members outside of the class. Thus we can rewrite the class as follows: private: int top; // Index of the top of the stack. int stack[10]; // The elements of the stack. ; Before, given a pointer to a Stack object, say s, any part of the program could access s->top, in potentially bad ways. Now, since the top member is private, only a member function, such as Full(), can access it. If any other part of the program attempts to use s->top the compiler will report an error. 3

You can have alternating and private: sections in a class. Before you specify either of these, class members are private, thus the above example could have been written: int top; // Index of the top of the stack. int stack[10]; // The elements of the stack. ; Which form you prefer is a matter of style. In many cases, it is best to make all data members of a class private and define accessor functions to read and write them. This adds to the modularity of the system, since you can redefine how the data members are stored without changing how you access them. 2.0.3 Constructors and the Operator new In C, in order to create a new object of type Stack, one might write: struct Stack * s = (struct Stack*) malloc(sizeof (struct Stack)); InitStack(s, 17); The InitStack() function might take the second argument as the size of the stack to create, and use malloc() again to get an array of 17 integers. The way this is done in C++ is as follows: Stack* s = new Stack(17); The new function takes the place of malloc(). To specify how the object should be initialized, one declares a constructor function as a member of the class, with the name of the function being the same as the class name: Stack(int sz); // Constructor: initialize variable, allocate space. private: int size; // The maximum capacity of the stack. int top; // Index of the lowest unused position. int *stack; // A pointer to an array that holds the contents. ; Stack::Stack(int sz) { size = sz; top = 0; stack = new int[size];// Let s get an array of integer. There are a few things going on here, so we will describe them one at a time. The new operators automatically creates (i.e. allocates) the object and then calls the constructor function for the new object. This same sequence happens even if, for instance, you declare an object as an automatic variable inside a function or block. (Some people avoid automatic allocation of object, to make it explicitly clear when the constructor is being called.) In this example, we create two stacks of different sizes, one by declaring it as an automatic variable, and one by using new. 4

void test() { Stack stack1(17); Stack* stack2 = new Stack(23); Note there are two ways of providing arguments to constructors: with new, you put the argument list after the class name. With variables declared as above, you put them after the variable name. The stack1 object is deallocated when the test function returns. The object pointed to by stack2 remains, however, until disposed of by using delete, described below. In this example it is inaccessible outside of test, and in a language like Lisp it would be garbage collected, but we could have returned stack2 as a value, for instance. Note how the new operator is used to allocate arrays, in this case an array of 10 ints: int * nums = new int[10]; Note that you can use new and delete (described below) with built-in types like int and char as well as with class objects. 2.0.4 Destructors and the Operator delete Just as new is the replacement for malloc(), the replacement for free() is delete. To get rid of the Stack object pointed to by s, one can do: delete s; This will deallocate the object, but first it will call the destructor for the Stack class, if there is one. This destructor would be a member function of Stack called ~Stack(): Stack(int sz); // Constructor: initialize variable, allocate space. ~Stack(); // Destructor: deallocate space allocated above. private: int size; // The maximum capacity of the stack. int top; // Index of the lowest unused position. int *stack; // A pointer to an array that holds the contents. ; Stack::~Stack() { delete stack; The destructor has the job of deallocating the data the constructor allocated. Most classes won t need destructors, and some will use them to close files and otherwise clean up after themselves. As with constructors, a destructor for an auto object will be called when that object goes out of scope (i.e., at the end of the function in which it is defined), so in the test() example above, the stack would be properly deallocated without you having to do anything. However, if you have a pointer to an object you got from new, and the pointer goes out of scope, then the object won t be freed you have to use delete explicitly. Since C++ doesn t have garbage collection, you should generally be careful to delete what you allocate. Many classes will not need destructors, and if you don t care about memory leaks (i.e., space not getting freed when it is no longer used) when one object allocates other objects and keeps pointers to them, you will need them even less frequently. 5

In some versions of C++, when you deallocate an array you have to tell delete how many elements there are in the array, like this: delete [size] stack; However, GNU C++ doesn t require this. 3 Other C++ Features Here are a few minor C++ features that are useful to know: 1. When you define a class Stack, the name Stack becomes usable as a type name as if created with typedef. The same is true for enums. 2. You can define functions inside a class definition, whereupon they become inline functions, which are expanded in the body of the function where they are used. This is usually a matter of convenience but it should not be overused. 3. Inside a function body, you can declare some variables, execute some statements, and then declare more variables. This can make code a lot more readable. In fact, you can even write things like: for (int i = 0; i < 10; i++); The variable i is still visible after the end of the for loop, however, which is not what one might expect or desire. 4. Comments can begin with the characters // and extend to the end of the line. These are usually more handy than the /* */ style of comments. 5. C++ has a different set of input/output operations. Data is read from or written to I/O streams, with the help of the read and write operators >> and <<. The default streams cin, cout, and cerr are for standard input, standard output, and for standard error. The following piece of C code #include<stdio.h> main() { char s[30]; printf("please enter s : "); scanf("%s", s); printf("you entered : %s", s); fprintf(stderr, "this goes to standard error"); looks as follows in C++: #include<iostream.h> main() { char s[30]; cout << "please enter s : "; cin >> s; cout << "you entered : " << s; cerr << "this goes to standard error"; Of course you can always keep using the C primitives for input output. 6

6. Friends have access to private members: A friend declaration within a class gives nonmember functions access to the private members of the class. By putting the line friend class A; into the declaration of class B gives the member functions of A access to the private members of B. 4 Style Guidelines It is as easy to write unreadable and undebuggable code in C++ as it is in C, and perhaps easier, given the more powerful features the language provides. For our projects, we suggest you adhere to the following few guidelines: 1. Minimize the use of global functions (as opposed to member functions). If you write a function that operates on some object (this will mostly be the case,) consider making it a member function of that object. 2. For every class or set of related classes, create a separate.h file and.c file. The.H file acts as the interface to the class, and the.c file acts as the implementation (a given.c file should include its respective.h file). If, for a particular.h file, you require another.h file to be included (e.g., process.h needs task.h) you should include it in the.h file, so that the user of your class does not have to track down all the dependencies herself. To protect against multiple inclusion, bracket each.h file with something like: #ifdef STACK H #define STACK H... ; #endif Sometimes this will not be enough, and you will have a circular dependency. In this case, you will have to do something ad-hoc: if you only use a pointer to class Stack and do not access any elements of the class, you can write, in lieu of the actual class definition: class Stack; This will tell the compiler all it needs to know to deal with the pointer. In a few cases this won t work, and you will have to move stuff around or alter your definitions. 5 Inheritance Inheritance in C++ allows to define classes as extensions of previously defined classes. The extension (called the base class) is said to inherit the variables and methods of the previous class (called the base class). The following is an example of a declaration of a class B derived from the base class A: class B : public A { <added members> ; The keyword public before the name of the base class specifies that, by default, the members inherited by class B from class A retain their visibility they had in class A. For example, a variable that is declared as public in class A is public in B as well. If it is private in class A on the other hand, it will not be accessible in class B (well, it is private in A after all). A nice thing about publicly derived classes is the following seemingly innocuous principle: 7

A object of a derived class can appear whereever an object of the public base class is expected. We note that classes can also be derived from private or protected base classes, by using the private or protected keyword in front of the name of the base class, but we are not going to use this. Object-oriented programming in C++ relies on virtual functions. Informally, the keyword virtual before a function declaration says: Use the function body in the derived class, whenever possible. The only difference between function f and g in the following pseudocode is that the keyword virtual appears before the declaration of f: class B { virtual char f() { return B ; char g() { return B ; char testf() { return f(); char testg() { return g(); ; The distinction between f and g will be tested using the following derived class, which redeclares f and g: class D : public B { char f() { return D ; char g() { return D ; ; The methods B::f and B::g return character B, and D::f and D::g return character D. The main function is main() { D d; cout << d.testf() << d.testg(); We remember that virtual fuctions are taken from the derived class where possible, so the body of B::testF calls D::f and returns D. On the other hand, g is not a virtual function, so the body of B::testG calls B::g and returns B. 6 Features Not Used At this point, we do not expect to use the following features of the language most of the code that we give you. If you use them, you are on your own. 1. Multiple Inheritance. This would probably be useful in some places, but it can be rather confusing. 2. Operator overloading. C++ lets you redefine the meanings of the operators (such as + and << for class objects. If used in non-intuitive ways, this can be a source of great confusion. 3. Function overloading. You can define different functions with the same name but different argument types. This is dangerous, and we use it only for constructors. 4. References. Reference variables are rather hard to understand in general. Their most common use is to declare some parameters to a function as reference parameters, like those in FORTRAN. This can be useful but is also a source of obscure bugs, and the semantics of references is in general not obvious. 8

5. Templates. Version 2 of C++ has templates as a way to define generic data structures (similar to ADA). This does not work very well with the GNU compiler suite, and are probably not necessary for the type of code that we will be writing in these projects. 6. Exceptions. Also new with Version 2. This is an easy call, since exceptions require runtime support, which we turn off to build the kernel. 9