Menu
Coddy logo textTech

Recap - String Class

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 26 of 104.

challenge icon

Challenge

Easy

Let's build a complete String class that manages its own dynamic character array, bringing together all the constructor and destructor concepts from this chapter. This is a classic exercise that mirrors how std::string works internally.

You'll create two files to organize your code:

  • String.h: Define your String class following the Rule of Five. Your class should manage a char* pointer called data and a size_t length member. Implement:
    • A default constructor that creates an empty string (allocate a single character for the null terminator, set length to 0). Print "Default constructed"
    • A parameterized constructor taking a const char* that copies the C-string into newly allocated memory. Print "Constructed: <text>"
    • A copy constructor that performs a deep copy of another String. Print "Copied: <text>"
    • A move constructor (marked noexcept) that transfers ownership. Print "Moved: <text>" using the text before nullifying the source
    • A destructor that safely frees memory (check for null). Print "Destroyed: <text>" (print "Destroyed: (empty)" if data is null or length is 0)
    • A size() method returning the length
    • A c_str() method returning the character pointer (return "" if null)
  • main.cpp: Demonstrate all constructors working together. Read a text string from input, then:
    • Create a String called s1 using the default constructor
    • Create a String called s2 with the input text
    • Create a String called s3 by copying s2
    • Create a String called s4 by moving from s2
    • Print "--- Status ---"
    • For each string (s1 through s4), print "s<n>: \"<text>\" (length: <len>)"

Use initializer lists in all constructors for efficiency. After the move, s2 should be empty with length 0, while s4 holds the original text. The destructor messages at the end will show all four objects being cleaned up in reverse order of creation.

Include <cstring> for strlen and strcpy, and <utility> for std::move(). Don't forget header guards in your header file.

Try it yourself

#include <iostream>
#include <string>
#include "String.h"

using namespace std;

int main() {
    string input;
    getline(cin, input);

    // TODO: Create String s1 using default constructor

    // TODO: Create String s2 with the input text

    // TODO: Create String s3 by copying s2

    // TODO: Create String s4 by moving from s2 (use std::move)

    // Print status header
    cout << "--- Status ---" << endl;

    // TODO: Print status for each string s1 through s4
    // Format: "s<n>: \"<text>\" (length: <len>)"

    return 0;
}

All lessons in Object Oriented Programming