A member variable is a type of class member for an in-class variable. For example, a Person class might have a member variable to hold a Person his/her name.
#include <string>
struct Person
{
std::string m_name;
//Other member variables
};
int main()
{
Person p;
p.m_name = "John Doe";
}
LocalVersusGlobal is a simple benchmark that tests the speed of local versus member variables versus global variables.
- Use a consistent method (such as a d_ prefix) to highlight member variables [1]
- Declare member variables private [2-5], except in PODs [4]
- Avoid member variables in abstract classes [6]
- Consider prefixing a private member variable with
m_
[7] - Initialize member variables with the member initializer list [8]
- [1] John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Chapter 2.7: 'Use a consistent method (such as a d_ prefix) to highlight class data members'
- [2] Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 22: Declare data members private.
- [3] Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 11: 'Hide information'.
- [4] Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 41: 'Make data members private, except in behaviourless aggregates (C-style structs).
- [5] John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0.
- [6] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 21.4. Advice. page 640: '[2] Avoid data members in base classes intended as interfaces'
- [7] Jason Turner, cppbestpractices: Distinguish Private Object Data
- [8] Jason Turner, cppbestpractices: Initialize Member Variables with the member initializer list