* 11.8, 11.9.
Friday's lecture
* Mike VanHilst - advanced C++ topics.
Final Exam
* Fri, Aug 18 (1:10 - 3:00).
* 110 minutes for 100 points (25% of your grade).
Office Hour Changes This Week
* No office hour on Friday (8/11).
* Extended office hour today (8/9) from 2:20 to 4:30pm.
Special Quiz
class Jar_Type {
// ...
};
class Labeled_Jar : public Jar_Type {
// ...
};
class Grocery_Store {
void insert(Jar_Type& jar1);
};
Jar_Type jar1;
Labeled_Jar jar2;
Grocery_Store store;
store.insert(jar1); // okay?
store.insert(jar2); // okay?
Dynamic Binding
* static binding = the determination of which function to call is done at compile time.
* dynamic binding = the determination of which function to call is done at run time!
* To get dynamic binding, the keyword "virtual" should be added to the member function of the base class.
* Some people consider this kind of run-time dependent behavior as the "polymorphic" behavior.
Declaration of virtual functions
class Jar_Type {
public:
virtual add (int in_n); // virtual function
private:
// ...
};
class Labeled_Jar : public Jar_Type {
public:
// virtual (is optional here)
add (int in_n);
private:
// ...
};
Dynamic binding is determined at run time
Jar_Type* m = new Jar_Type;
m->add(20);
cout << m->get_size() << endl;
// answer is 20, assume jar_p->units starts with 0.
Jar_Type* n = new Labeled_Jar("magic beans");
m->add(20);
cout << m->get_size() << endl;
// answer is ?
* Dynamic binding occurs ONLY with
1. pointer variables, and
2. reference variables.
How about this?
void fun(Jar_Type jar)
{
jar.add(20);
// which Jar class's add function is invoked?
}
void fun(Jar_Type& jar)
{
jar.add(20); // which is invoked?
}
void fun(Jar_Type* jar_p)
{
jar_p->add(20); // which is invoked?
}
Deallocating dynamic data
* Virtual destructor - results in dynamic binding when the "delete" operator executes.
* Syntax:
class Base {
public:
virtual ~Base();
};
class Derived : public Base {
public:
virtual ~Derived();
};
Base * p = new Derived;
delete p; // which destructor(s) is invoked?
Base b;
// which destructor(s) is invoked when b is out
// of scope?