When to Use Whole-object Member Variables

While it’s usually best to use pointers for member variables rather than storing them by value, sometimes it’s better to store the member as a whole object, that is, to store it by value. Here are some situations where this is true:

  • When the header file for the member’s class has to be included anyway?perhaps to satisfy some other part of the same class definition.
  • When the member is a built-in type, like an integer.
  • When the member is small.
  • If you want to save memory from heap manager overhead, as when many objects of the class that holds this member are likely to be in existence at the same time. Note that typical heaps require at least a dozen bytes in overhead per object allocated, which may actually be larger than the memory actually used as payload in the heap block.
  • In order to improve performance in allocating the object, as when objects of the class will be allocated and destroyed frequently.
  • In special situations when the object is meant for use when it is unsafe to access the heap and must be allocated purely on the stack or into memory previously allocated by the user using the placement new syntax. An example of this would be C++ objects constructed at interrupt time in the classic Mac OS.

An important instance in which you cannot store a member by value is when the member is being used polymorphically (especially when the base class contains a pure virtual function?then the class declaration will fail to compile). You will usually want a pointer to the member’s base class in this case.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS