You are on page 1of 2

C/C++ Cheat Sheet

For your reference; this sheet will also be included in exams


CISC 124, fall 2004

Sample C++ Program: class Salesperson: public Employee {


#include <stdio.h> private:
#include <string.h> double rate;
class Employee { public:
private: Salesperson(char name[],
char name[51]; double wage,
double wage; // hourly wage double rate)
protected: : Employee(name, wage) {
double payOwed; this->rate = rate;
public: } // end constructor
Employee(char n[], double w) {
strcpy(name, n); void payForSale(double amount) {
setWage(w); payOwed += amount * rate;
payOwed = 0; } // end payForSale
} // end constructor
void print() {
virtual void pay(double hours) { printf("Salesperson ");
payOwed += wage * hours; Employee::print();
} // end pay printf(", rate: $%.2f\n", rate);
} // end print
double amountToPay() {
return payOwed; }; // end Salesperson
} // end amountToPay
int main(void) {
void setWage(double wage) { Employee mickey("Mickey Mouse", 20);
this->wage = wage; mickey.setWage(21);
} mickey.println();

void zero() { Salesperson *donald =


payOwed = 0; new Salesperson("Donald Duck",
} // end zero 10, 0.15);
donald->payForSale(100);
// prints employee donald->println();
virtual void print() { Employee *company[2];
printf("name = %s, ", name); company[0] = &mickey;
printf("wage = $%.2f, ", wage); company[1] = donald;
printf("payOwed = $%.2f", for (int i = 0; i < 2; i++) {
payOwed); company[i]->pay(10);
} // end print company[i]->println();
} // end for
void println() { } // end main
print();
printf("\n");
} // end println

}; // end class Employee


printf formats:
%d: integer
%f: float or double
%s: string (char array)
%c: char (single character)

scanf formats:
%d: integer
%f: float
%lf: double (first character is L, not one!)
%s: string (char array)
%c: char (single character)

string methods:
/* to use these methods, you
must include <string.h> */
strcpy(char dest[], char src[])
copies src into dest
int strlen(char s[])
returns length of s
int strcmp(char s1[], char s2[])
returns negative if s1 < s2,
0 if s1 == s2
positive if s1 > s2
strcat(char dest[], char src[])
adds src to the end of dest

abstract classes and methods:


virtual void sound(char s[]) = 0;
// Reminder: no "abstract" keyword.
// Class headers do not indicate
// whether the class is abstract or
// not. A class is abstract if it
// contains any abstract methods.

You might also like