CS 330 Lecture 20 – C++
Agenda
Think About This
Does this code compile?
class A {
A tweakTweak(int a) {
return new A();
}
}
class B extends A {
@Override
B tweakTweak(int a) {
return new B();
}
}
How about this code?
class A {
A tweakTweak(int a) {
return new A();
}
}
class C extends A {
@Override
A tweakTweak(double a) {
return new A();
}
}
C with Classes
class PegasusBoots {
public:
PegasusBoots(int strength) {
this->strength = strength;
}
int getStrength() const {
return strength;
}
void engage(Hero h) {
h.setJumpFactor(getStrength());
}
static const std::string& getPartNumber() {
return "#JF1273";
}
private:
int strength;
}
Polymorphism without Conditions
- http://www.antiifcampaign.com
- http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html
Code
Function.h
#ifndef FUNCTION_H
#define FUNCTION_H
class Function {
public:
virtual double EvaluateAt(double x) const = 0;
};
#endif
SineFunction.h
#ifndef SINEFUNCTION_H
#define SINEFUNCTION_H
#include "Function.h"
class SineFunction : public Function {
public:
double EvaluateAt(double x) const;
};
#endif
SineFunction.cpp
#include <iostream>
#include <cmath>
#include "SineFunction.h"
/* ------------------------------------------------------------------------- */
double SineFunction::EvaluateAt(double x) const {
return sin(x);
}
/* ------------------------------------------------------------------------- */
graph_drawer.cpp
#include <iostream>
#include "Function.h"
#include "SineFunction.h"
/* ------------------------------------------------------------------------- */
void draw(const Function &f);
/* ------------------------------------------------------------------------- */
int main(int argc, char **argv) {
SineFunction sine;
draw(sine);
return 0;
}
/* ------------------------------------------------------------------------- */
void draw(const Function &f) {
const int NROWS = 21;
const int NCOLS = 51;
char plot[NROWS][NCOLS];
for (int r = 0; r < NROWS; ++r) {
for (int c = 0; c < NCOLS; ++c) {
plot[r][c] = ' ';
}
}
for (int c = 0; c < NCOLS; ++c) {
plot[NROWS / 2][c] = '-';
}
for (int r = 0; r < NROWS; ++r) {
plot[r][NCOLS / 2] = '|';
}
plot[NROWS / 2][NCOLS / 2] = '+';
for (int c = 0; c < NCOLS; ++c) {
double x = c / (NCOLS - 1.0) * 6.0 - 3.0;
double y = f.EvaluateAt(x);
int r = (int) (y * NROWS * 0.5 + NROWS * 0.5);
if (r >= 0 && r < NROWS) {
plot[r][c] = '.';
}
}
for (int r = NROWS - 1; r >= 0; --r) {
for (int c = 0; c < NCOLS; ++c) {
std::cout << plot[r][c];
}
std::cout << std::endl;
}
}
/* ------------------------------------------------------------------------- */
Haiku
Dad said, “You can’t go”
I went and dug up his dad
“Gramps, make him say yes”
I went and dug up his dad
“Gramps, make him say yes”