This preview shows page 1. Sign up to view the full content.
Unformatted text preview: sing
the default constructor of the class. x directly names this object; it is not a pointer.
• To put it another way, C++ treats primitive types and classes similarly, whereas Java
treats them differently. Compare the semantics of these declarations in C++ vs. Java:
C x;
int a; x: Storage for x Scott B. Baden / CSE 100, Lec 2 / Spring 2013 47 Arithmetic and boolean operators in C++
• C++ has all the arithmetic operators that Java has, and they work similarly:
+  * / % ++  • C++ has all the comparison and boolean operators that Java has, too:
< > == >= <= &&  !
• However, these operators work a bit differently, because of how C++ deals with
boolean values • One important feature of C++ operators is that they can be overloaded: you can write
your own definitions of them
• Also note Java’s left to right evaluation order: foo( ) is evaluated before bar( )
a = foo( ) + bar ();
• C++ doesn’t specify which will be evaluated first Scott B. Baden / CSE 100, Lec 2 / Spring 2013 48 Iterative and conditional control constructs in C++
• C++ has all the iterative and conditional control constructs that Java has:
if ifelse while dowhile for switch • These work basically like their Java counterparts, except for some differences related to
how C++ handles boolean expressions Scott B. Baden / CSE 100, Lec 2 / Spring 2013 49 Boolean expressions in C++
• C++ provides a primitive type bool, and literals true, false
• However, in every context these are equivalent to integral values where 0 means
"false", and any nonzero value means "true"
• Assuming the following declarations...
int num = 3;
double x = 4.0; • ... what are the values of these expressions?
num == 3
x > num
x > num
&&
num == 3
!(x > num) && num == 3
1 && 37
x > num > 0 1
1
1
0
1
1 Scott B. Baden / CSE 100, Lec 2 / Spring 2013 50 Boolean expressions in C++, cont’d
• The fact that integer values are interpreted as booleans means you can write some terse
(and maybe hard to understand) code in C++. For example, in the recursive version of
factorial, you could write:
// precondition:
n >= 0
int factorial(int n) {
if(n) return (n * factorial(n1));
else return 1;
} • It also means you can introduce hardtosee bugs. What does the following version of
factorial do (note this will compile in C++ but not Java)?
// precondition:
n >= 0
int factorial(int n)
if(n=0) return 1;
else return (n * factorial(n1));
} Scott B. Baden / CSE 100, Lec 2 / Spring 2013 51 Next time
•
•
•
•
• The “const” qualifier
Arrays, pointers and pointer arithmetic
The interface/implementation distinction in C++
C++ class templates
“friend” visibility
Reading: Weiss Ch 1, the slides passed over
quickly today Scott B. Baden / CSE 100, Lec 2 / Spring 2013 52...
View
Full
Document
 Spring '08
 staff
 Data Structures

Click to edit the document details