Search

12.x — Chapter 12 comprehensive quiz

And so our journey through C++’s inheritance and virtual functions comes to an end. Fret not, dear reader, for there are plenty of other areas of C++ to explore as we move forward.

Chapter summary

C++ allows you to set base class pointers and references to a derived object. This is useful when we want to write a function or array that can work with any type of object derived from a base class.

Without virtual functions, base class pointers and references to a derived class will only have access to base class member variables and versions of functions.

A virtual function is a special type of function that resolves to the most-derived version of the function (called an override) that exists between the base and derived class. To be considered an override, the derived class function must have the same signature and return type as the virtual base class function. The one exception is for covariant return types, which allow an override to return a pointer or reference to a derived class if the base class function returns a pointer or reference to the base class.

A function that is intended to be an override should use the override specifier to ensure that it is actually an override.

The final specifier can be used to prevent overrides of a function or class.

If you intend to use virtual functions, you should make your destructor virtual, so the proper destructor is called if a pointer to the base class is deleted.

You can ignore virtual resolution by using the scope resolution operator to directly specifying which classes version of the function you want: e.g. base.Base::getName()

Early binding occurs when the compiler encounters a direct function call. The compiler or linker can resolve these function calls directly. Late binding occurs when a function pointer is called. In these cases, which function will be called can not be resolved until runtime. Virtual functions use late binding and a virtual table to determine which version of the function to call.

Using virtual functions has a cost: virtual functions take longer to call, and the necessity of the virtual table increases the size of every object containing a virtual function by one pointer.

A virtual function can be made pure virtual/abstract by adding “= 0” to the end of the virtual function prototype. A class containing a pure virtual function is called an abstract class, and can not be instantiated. A class that inherits pure virtual functions must concretely define them or it will also be considered abstract. Pure virtual functions can have a body, but they are still considered abstract.

An interface class is one with no member variables and all pure virtual functions. These are often named starting with a capital I.

A virtual base class is a base class that is only included once, no matter how many times it is inherited by an object.

When a derived class is assigned to a base class object, the base class only receives a copy of the base portion of the derived class. This is called object slicing.

Dynamic casting can be used to convert a pointer to a base class object into a pointer to a derived class object. This is called downcasting. A failed conversion will return a null pointer.

The easiest way to overload operator<< for inherited classes is to write an overloaded operator<< for the most-base class, and then call a virtual member function to do the printing.

Quiz time

1) Each of the following programs has some kind of defect. Inspect each program (visually, not by compiling) and determine what is wrong with the program. The output of each program is supposed to be “Derived”.

1a)

Show Solution

1b)

Show Solution

1c)

Show Solution

1d)

Show Solution

1e)

Show Solution

1f)

Show Solution

2a) Create an abstract class named Shape. This class should have three functions: a pure virtual print function that takes and returns a std::ostream, an overloaded operator<< and an empty virtual destructor.

Show Solution

2b) Derive two classes from Shape: a Triangle, and a Circle. The Triangle should have 3 Points as members. The Circle should have one center Point, and an integer radius. Overload the print() function so the following program runs:

This should print:

Circle(Point(1, 2, 3), radius 7)
Triangle(Point(1, 2, 3), Point(4, 5, 6), Point(7, 8, 9))

Here’s a Point class you can use:

Show Solution

2c) Given the above classes (Point, Shape, Circle, and Triangle), finish the following program:

Hint: You’ll need to add a getRadius() function to Circle, and downcast a Shape* into a Circle* to access it.

Show Solution

13.1 -- Function templates
Index
12.10 -- Printing inherited classes using operator<<

99 comments to 12.x — Chapter 12 comprehensive quiz

  • Hello Alex,
    can i work with pointers only for this code

    i mean references is like taking a const pointer to each vector element right (which is a pointer)

    so this is not equivalent to:

    i need to make a pointer to pointer to match the first code correct ?

    • > element will be a const reference to a Shape*
      Correct

      > i need to make a pointer to pointer to match the first code correct ?
      No. After compilation, references turn into pointers. Before that, you should look at them like aliases. @element is a

      EDIT: 1-line

      • i do not understand, i thought that const Shape* const &Elem is the same as auto const &element
        i understand after compilation references turn to pointers but doesn't that makes this case a pointer to another pointer,
        i think i'am confused as the pointer element is copied then deleted by another pointer or is deleted by the same pointer thru pointer to pointer ?

        • There's only 1 pointer here.
          Your first loop is equivalent to

          Calling @delete on a reference is the same as calling @delete on the object that is referenced by the reference.

          EDIT: 1-line

  • jason guo

    My solution.

    How come dynamic cast doesn't work on line 89?

    • * Line 23, 24, 25, 86, 87, 109: Initialize your variables with brace initializers. You used copy initialization.
      * Line 100, 101, 102: Initialize your variables with brace initializers. You used direct initialization.
      * Line 66, 67: Initialize your variables with brace initializers.
      * Line 106: Limit your lines to 80 characters in length for better readability on small displays.
      * @Triangle::Triangle: Use member initializer lists.
      * Enable compiler warnings, read them, fix them. (Lesson 0.10, 0.11)
      * Inconsistent formatting. Use the auto-formatting feature of your editor.
      * Inconsistent naming. Pick a naming convention, stick to it.
      * Line 89: Should use @dynamic_cast.

      > How come dynamic cast doesn't work on line 89?
      If the types are incompatible, @dynamic_cast returns @nullptr. Since @a stores pointer to objects that are not Cicles, at some point a nullptr will be returned. You're not checking if the cast was successful.

  • Dants

    hi

    In @getLargestRadius

    how exactly does the statement "Circle *c = dynamic_cast<Circle*>(element)" get evaluated as a boolean value ?

    Thanks

    • Hi Dants!

      It casts @c to a bool. Pointers evaluate to true if they are not null pointers. It's equivalent to

      Note: Brace initializers should be used

      The same can be done with all types that are convertible to bool.

      If you want your code to be more obvious, you can also use an initializer statement in the if:

  • lucieon

    In Quiz 2, what happens inside the default destructor of classes Triangle and Circle?
    I mean there is not any dynamically allocated memory in those classes so what's the point of making ~Shape() virtual?

    • Alex

      It's a best practice to have a virtual destructor if any functions in the class are virtual.

      That way, if you later derive from Shape, Triangle, or Circle, and do allocate dynamic memory (or do anything else that needs to be cleaned up) your derived class will be able to do so properly.

  • Faruk

    Hi i coded a hangman game.I went very good.Any tips or code improvements.

    ASCII_Graphics.hpp

    Main.cpp

    • When you don't have a reason not to, you should use what is supplied by the std library (@std::string).

      ASCII_Graphics.hpp
      * Line 48, 63, 104, 118, 119, 123, 143: Initialize your variables with uniform initialization. You used copy initialization.
      * Line 7, 8, 14, 93, 94, 95: Initialize your variables with uniform initialization.
      * Code belongs is source files. Header files are for declarations.
      * Structs should not have member functions. That's what classes are there for.
      * Don't use @malloc, @free. Use @new, @delete.
      * @malloc, @memcpy, @free, @strlen should be replaced by their namespaced counterparts.
      * Missing include to @<cstring> for @std::malloc, @std::memcpy, etc.
      * @String::String(const String&) could be delegated to @String::String(const char*)
      * You're using a mix of C-functions and manual code (Not using @std::memcmp). Pick one, stick to it.
      * @String is missing assignment overloads
      * @String::Contains Parameters (except @index) should be const.
      * @String::Contains is specialized to your game. It should not be a member of @String.
      * Line 65: @this->Str_Buffer[i] doesn't have to exist.
      * Inconsistent use of @this
      * Use enum class instead of enum
      * Line 104: You don't have to specify the array size when initializing arrays.
      * Use C++ casts. (@static_cast, @reinterpret_cast, @dynamic_cast)
      * Magic number: 24
      * Use ++prefix unless you need postfix++
      * Don't use @system. "cls" is a Windows-exclusive command.
      * Don't compare booleans to false/true. They're booleans already.

      Main.cpp
      * Line 8, 27, 28, 36, 50, 60, 69: Initialize your variables with uniform initialization. You used copy initialization.
      * Line 15: Initialize your variables with uniform initialization.
      * @getRandomNumber::fraction should be constexpr
      * Use @std::rand, @std::srand, @std::time instead of their non-namespaced counterparts.
      * @std::time expects a pointer as it's argument. Pass @nullptr.
      * You're using the same name style for functions and variables. This can lead to confusion.
      * Line 32: Why initialize to a space?
      * Magic number: 8

      Please post your quiz solutions in future lessons so you don't get used to your current code style.

      • Faruk

        Thank you for your feed back.But i have a question about why should i use a class instead of a struct.Structs and Classes are the same thing the difference is the classes are private by default, and structs are public.

    • magaji::hussaini

      That was cool. Nice...

  • Arumikaze

    Hello! I am 99% sure I did everything correctly, but if you can please check my code I would greatly appreciate it. Thank you so much!

    shape.h

    point.h

    circle.h

    triangle.h

    main.cpp

    Again, sorry for the long post. I am trying to get into the habit of having them in separate files.

    • Hi Arumikaze!

      Every header
      * If you're going to write definitions in header files, you might as well write the definitions inside the class. Write declarations in header files, definitions in source files. Default arguments should be part of the declaration.

      General
      * I don't see the point of the @print function, you could've used @operator<< directly.
      * Good use of uniform initialization
      * Good use of dynamic memory
      * Good use of const/reference

      Future
      * @getLargestRadius: Have a look at @std::max_element

      References
      std::max_element - http://www.cplusplus.com/reference/algorithm/max_element/

  • David

    Hi Alex! Thanks for the great quiz. Two quick questions:

    First, why do we need the continue statement in the getLargestRadius() function? I think the following is a little simpler:

    Second, does this part of your program only delete the Shape portion of each element of the vector? (i.e. are the Circle and Triangle parts leaked?)

    • Jack

      Obviously not Alex, just a fellow learner like you, so take what I say with a pinch of salt as may not be fully correct.

      1) I wrote my function the same way as you. I suppose the extra 'continue' can indicate clearer intention, but your version is by no means unclear. Same meat different gravy.

      2) Notice that in @Point:

      The vector is a vector of Shape*. Therefore we do not call the destructor of Shape, but the most-derived version of the destructor (that is, Circle or Triangle).

      As mentioned, I'm also just a learner, but that is what I understood of the lessons. Hopefully someone more knowledgeable can confirm.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]