
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Rule Of Three in C++
The Rule of three is a rule of thumb when using C++. This is kind of a good practice rule that says that If your class needs any of
- a copy constructor,
- an assignment operator,
- or a destructor,
defined explicitly, then it is likely to need all three of them.
Why is this? It’s because, if your class requires any of the above, it is managing dynamically allocated resources and would likely be needing the other to successfully achieve that. For example, if you require an assignment operator, you would be creating copies of objects currently being copied by reference, hence allocating resources. You'll need the copy constructor for copying and destructor for freeing up these resources.
1. copy constructor − The compiler-supplied copy constructor does a member-wise copy of all the Foo Manager’s attributes. This poses the same problems as the assignment operator.
2. assignment operator − If you do not provide one the compiler creates a default assignment operator. The default assignment operation is a member-wise copy function and does a shallow copy and not a deep copy. This could cause problems like memory leaks, wrong assignment.
3. destructor − When this manager goes out of scope it should free all the resources it was managing.
- Related Articles
- Rule of Three vs Rule of Five in C++?
- C++ Rule Of Three.
- What is The Rule of Three with reference to C++?
- What is Rule of Five in C++11?
- Rule of Law
- Largest Multiple of Three in C++
- Effects of Colonial Rule
- Intersection of Three Sorted Arrays in C++
- Maximum Product of Three Numbers in C++
- Current Divider Rule and Voltage Divider Rule
- The north-south polarities of an electromagnet can be found easily by using:(a) Fleming's right-hand rule(b) Fleming's left-hand rule (c) Clock face rule (d) Left-hand thumb rule
- Usage of CSS !important rule
- Usage of CSS @charset rule
- Usage of CSS @import: rule
- Explain divisibility rule of 8.
