Implement or get special member functions defaulted

Hi,

In what situations would you implement your class's special member functions?
Suppose there's a class like:
1
2
3
4
5
6
7
8
template <typename T>
class myClass {
public:
    // special and other member functions
private:
T* p {nullptr};
double d{};
};
Last edited on
In what situations would you implement your class's special member functions?

If and only if the compiler-generated implementation doesn't do what you want/need 😏

Special member functions in C++ are functions which the compiler will automatically generate if they are used, but not declared explicitly by the programmer. The automatically generated special member functions are:
- Default constructor
- Copy constructor
- Move constructor
- Move assignment operator
- Destructor
- The 'address of' operator (unary '&' operator)

https://en.wikipedia.org/wiki/Special_member_functions


Example: Suppose that you have a custom "String" class that internally stores a pointer to the actual text data, which is allocated on the heap. Now, the compiler-generated copy constructor would simply copy each field of the class, so that the "copy" of the String would contain the same pointer as the "original" instance; both instances would be pointing to the same heap location. Modifying the "original" string would therefore effect the "copy", and vice versa! In this situation, you probably want to implement your own copy constructor that actually duplicates the string data on the heap and that gives the "copy" of the String its own separate memory buffer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyString
{
public:
	// What the compiler-generated copy constructor would do:
	MyString(const MyString& other)
	{
		m_buffer = other.m_buffer; // 😱
	}

	// What you probably *want* the copy constructor to do:
	MyString(const MyString& other)
	{
		m_buffer = new char[strlen(other.m_buffer) + 1U];
		strcpy(m_buffer, other.m_buffer);
	}

protected:
	char *m_buffer;
};

Of course, you also want to implement an explicit destructor that properly frees the memory buffer!
Last edited on
If the class holds at least one pointer variable then you'll probably need to implement your own constructor(s), destructor and the special assignment operator (if allowed) as the default copy will do a shallow copy whereas you'll probably need a deep copy. IF you don't want your class to be copied etc then you can mark those not wanted as =delete and you'll get a compile error if they are used.

Topic archived. No new replies allowed.