Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Exercise #3: Don't give away your internals

 

Difficulty: 3/10

Date added: 16th of June 2008

 

In this exercise, you must follow the following advice: 'Don't give away your internals' [1]. You will learn something about method design and a 'loophole' in constness.

 

 

 

 

 

Part #0: checking your member function design

 

You are programming on a Zoo class, containing a std::vector of Animal. An Animal is an ordinary struct containg member variables only (also called a plain old data type). Your code so far is shown below.

 

#include <vector>

struct Animal {}; //A plain old data type

struct Zoo
{
  private:
  std::vector<Animal> mAnimals;
};

 

Write a member function called 'GetAnimals' to read, and only read, the std::vector of Animal.

 

View the answer of this exercise.

 

 

 

 

 

Part #1: checking you checking

 

You still work on the same Zoo and Animal class. But you redesigned Animal to be an abstract base class. You have decided to store pointers to Animal in a boost::shared_ptr. Your redesigned code is shown below.

 

#include <vector>
#include <boost/shared_ptr.hpp>

struct Animal { }; //An abstract base class

struct Zoo
{
  private:
  std::vector<boost::shared_ptr<Animal> > mAnimals;
};

 

Write a member function called 'GetAnimals' to read, and only read, the std::vector of boost::shared_ptr of Animal. Check this method.

 

View the answer of this exercise.

 

 

 

 

 

Post your feedback

 

Feedback can be posted at the Programmer's Heaven page about this article.

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 28: 'Don't give away your internals'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict