Recap - String Class
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 26 of 104.
Challenge
EasyLet'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 yourStringclass following the Rule of Five. Your class should manage achar*pointer calleddataand asize_t lengthmember. 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)
- A default constructor that creates an empty string (allocate a single character for the null terminator, set length to 0). Print
main.cpp: Demonstrate all constructors working together. Read a text string from input, then:- Create a
Stringcalleds1using the default constructor - Create a
Stringcalleds2with the input text - Create a
Stringcalleds3by copyings2 - Create a
Stringcalleds4by moving froms2 - Print
"--- Status ---" - For each string (s1 through s4), print
"s<n>: \"<text>\" (length: <len>)"
- Create a
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
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container