CS 106X Classes and Objects: Guest Presenter: Marty Stepp (Stepp AT Cs DOT Stanford DOT Edu)
CS 106X Classes and Objects: Guest Presenter: Marty Stepp (Stepp AT Cs DOT Stanford DOT Edu)
guest presenter:
Marty Stepp (stepp AT cs DOT stanford DOT edu)
reading:
Programming Abstractions in C++, Chapter 6
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others.
Class examples
• A calendar program might want to store information
about dates, but C++ does not have a Date type.
2
Classes and objects (6.1)
• class: A program entity that represents
a template for a new type of objects.
– e.g. class Vector defines a new data type
named Vector and allows you to declare
objects of that type.
4
Elements of a class
• member variables: State inside each object.
– Also called "instance variables" or "fields"
– Declared as private
– Each object created has a copy of each field.
6
Structure of a .h file
// classname.h
#ifndef _classname_h
This is protection in case
#define _classname_h multiple .cpp files include this .h,
so that its contents won't
get declared twice
class declaration;
#endif
7
A class declaration
class ClassName { // in ClassName.h
public:
ClassName(parameters); // constructor
private:
type name; // member variables
type name; // (data inside each object)
};
class BankAccount {
public:
string name; // each BankAccount object
double balance; // has a name and balance
};
#endif
9
Using objects
// v1 with public fields (bad)
BankAccount ba1; ba1
ba1.name = "Marty"; name = "Marty"
ba1.balance = 1.25; balance = 1.25
10
Member func. bodies
• In ClassName.cpp, we write bodies (definitions) for the member
functions that were declared in the .h file:
// ClassName.cpp
#include "ClassName.h"
// member function
returnType ClassName::methodName(parameters) {
statements;
}
– We are able to this with most types of objects in C++ and Java.
– You can achieve this functionality using a constructor.
14
Constructors
ClassName::ClassName(parameters) {
statements to initialize the object;
}
15
Constructor diagram
// BankAccount.cpp
BankAccount::BankAccount(string n, double b) {
name = n;
balance = b;
} name balance
BankAccount(string n, double b) {
name = n;
// client program balance = b;
}
BankAccount b1(
"Marty", 1.25);
name balance
BankAccount b2(
"Mehran", 9999); BankAccount(string n, double b) {
name = n;
balance = b;
}
16
The keyword this
• As in Java, C++ has a this keyword to refer to the current object.
– Syntax: this->member
BankAccount::BankAccount(string name,
double balance) {
this->name = name;
this->balance = balance;
}
this uses -> not . because it is a "pointer"; we'll discuss that later
17
Preconditions
• precondition: Something your code assumes is true
at the start of its execution.
– Often documented as a comment on the function's header:
18
Throwing exceptions
throw expression;
22
Operator overloading (6.2)
• C++ allows you to overload, or redefine, the behavior of many
common operators in the language:
– unary: + - ++ -- * & ! ~ new delete
– binary: + - * / % += -= *= /= %= & | && || ^
== != < > <= >= = [] -> () ,
23
Op overload syntax
• Declare your operator in a .h file, implement it in a .cpp file.
Overloaded operators can also be declared inside a class (not shown here)
24
Op overload example
// BankAccount.h
class BankAccount {
...
};
bool operator ==(BankAccount& ba1, BankAccount& ba2);
bool operator !=(BankAccount& ba1, BankAccount& ba2);
// BankAccount.cpp
bool operator ==(BankAccount& ba1, BankAccount& ba2) {
return ba1.getName() == ba2.getName()
&& ba1.getBalance() == ba2.getBalance();
}
bool operator !=(BankAccount& ba1, BankAccount& ba2) {
return !(ba1 == ba2); // calls operator ==
}
25
Make objects printable
• To make it easy to print your object to cout, overload the <<
operator between an ostream and your type:
26
<< overload example
// BankAccount.h
class BankAccount {
...
};
ostream& operator <<(ostream& out, BankAccount& ba);
// BankAccount.cpp
ostream& operator <<(ostream& out, BankAccount& ba) {
out << ba.getName() << ": $"
<< setprecision(2) << ba.getBalance();
return out;
}
27
The keyword const
• C++ const keyword indicates that a value cannot change.
const int x = 4; // x will always be 4
28
Overflow (extra) slides
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others.
Class constants
• To make a class constant, declare a static variable in the .h file.
– Assign its value in the .cpp, outside of any method.
– Don't write static or const when assigning the value in the .cpp.
// BankAccount.h
class BankAccount {
static const double INTEREST_RATE;
};
// BankAccount.cpp
double BankAccount::INTEREST_RATE = 0.0325; // 3.25%
30
Structs
• C++ also has an entity called a structure (struct).
– Very similar to a class; a collection of data and (maybe) behavior.
– But has (by default) public fields and no methods.
struct Point {
int x;
int y;
};
...
Point p;
p.x = 15;
...
32