Sams Teach Yourself C++ in 21 Days

(singke) #1

Day 12


Quiz


  1. A v-table, or virtual function table, is a common way for compilers to manage vir-
    tual functions in C++. The table keeps a list of the addresses of all the virtual func-
    tions, and depending on the runtime type of the object pointed to, invokes the right
    function.

  2. A destructor of any class can be declared to be virtual. When the pointer is deleted,
    the runtime type of the object will be assessed and the correct derived destructor
    invoked.

  3. This was a trick question—there are no virtual constructors.

  4. By creating a virtual method in your class, which itself calls the copy constructor.
    5.Base::FunctionName();
    6.FunctionName();

  5. Yes, the virtuality is inherited and cannot be turned off.
    8.protectedmembers are accessible to the member functions of derived objects.


Exercises

1.virtual void SomeFunction(int);


  1. Because you are showing a declaration of Square, you don’t need to worry about
    Shape. Shapeis automatically included as a part of Rectangle.
    class Square : public Rectangle
    {};

  2. Just as with Exercise 2, you don’t need to worry about Shape.
    Square::Square(int length):
    Rectangle(length, width){}

  3. The following is one possible answer:
    class Square
    {
    public:
    // ...
    virtual Square clone() const { return new Square(this); }
    // ...
    };

  4. Perhaps nothing. SomeFunctionexpects a Shapeobject. You’ve passed it a
    Rectangle“sliced” down to a Shape. As long as you don’t need any of the


846 Appendix D

32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 846

Free download pdf