Professional Documents
Culture Documents
Get & Set Functions Can Get & Set Abstract Data
• You should not allow clients to access • Maintain abstract concepts
member variables directly.
class TankCar {
• Use get & set functions public: double radius, length;
double getRadius() { return radius; }
class TankCar { double getLength() { return length; }
public: double radius, length; void setRadius(double r) { radius = r; }
double getRadius() { return radius; } void setLength(double l) { length = l; }
double getLength() { return length; } double getDiameter(){ return 2.0 * radius; }
void setRadius(double r) { radius = r; } void setDiameter(double d){ radius = d / 2.0 }
void setLength(double l) { length = l; } };
};
1
Client Can’t Modify “Privates” Inheritance
class TankCar {
public: • We have two railcars defined: BoxCar and
double getRadius() { return radius; } TankCar.
double getLength() { return length; }
void setRadius(double r) { radius = r; } • Adding a shared concept means adding it
void setLength(double l) { length = l; }
double getDiameter(){ return 2.0 * radius; }
to both classes
void setDiameter(double d){ radius = d / 2.0 } • eg: adding “percent full” to concept of
private:
double radius, length; railcar means adding a data member to
}; both classes.
main() {
TankCar t; • We move shared concepts to a “higher
t.radius = 8.0; // this line won’t compile level” class.
t.setRadius(8.0); // this is how it’s done
…
2
Shadowing: Example When to Use Inheritance
class Bird {
public: void speak() { cout << “beep beep beep”; } • When they parallel natural categories
}; • Prevent avoidable duplication
class Duck : public Bird {
public: void speak() { cout << “quack quack”; } • Simplify maintenance
};
main() { • Avoid introducing bugs to debugged code
Bird b;
Duck d;
• Use purchased code
b.speak(); // beep
d.speak(); // quack
d.Bird::speak(); // beep
}