CS 330 Lecture 21 – First C++
March 26, 2012 by Chris Johnson. Filed under cs330, lectures, spring 2012.
Agenda
- what do you know about C++?
- C++ roots: Simula
- Bjarne Strostroup
- TIOBE index for C++
- values vs. pointers vs. references (which?)
- classes in C++
- mapping between C with Classes and C
- can be made on stack
- for heap, why new/delete? (RAII)
- access control
- constructor/deconstructor
- use initialization lists
- default constructor
- copy constructor
- an example class: FasterString
- Bjarne’s goal in C++: type parity
- custom classes on stack or heap, unlike Simula
- can overload builtin operators to work with classes
TODO
Code
FasterString.cpp
class FasterString {
public:
FasterString();
FasterString(const char *src);
const char *GetCString();
private:
char *characters;
int length;
};
FasterString::FasterString() :
characters(NULL),
length(0) {
}
FasterString::FasterString(const char *src) :
length(strlen(src)),
characters(NULL) {
/* characters = malloc(sizeof(char) * length); */
characters = new char[length];
memcpy(characters, src, length * sizeof(char));
}
const char *FasterString::GetCString() {
return characters;
}
int main() {
FasterString f("hi, jeff");
// ctor has already been called, and f is valid
std::cout << "f.GetCString(): " << f.GetCString() << std::endl;
return 0;
}
Haiku
Errors and classes.
What happens when they marry?
Objections are raised.
show