<<< Correct implementation for the Rectangle | Index | >>> |
We made a lot of effort making the Rectangle struct allocate and deallocate dynamic memory for a tiny string of characters.
In Java, every "string literal" is an object, lifting the burden of low-level memory allocation/dealocation off the programmer's shoulders.
Likewise, in C++, there is a C++ standard library string class that manages a variable-sized string of characters.
In the following demo, I replaced the pointer to a string of characters with std::string.
The copy constructor, the move constructor, and overloaded assignment operator are removed, because by default, compiler-generated version of copy, move, and assignment invoke similar operations for every data member of the struct. In our case the work is delegated to the the implementation of the standard library string class:
#include <cstdlib> #include <iostream> #include <string> struct Rectangle { int width; // member variable int height; // member variable std::string name; Rectangle() : width( 1 ), height( 1 ), name( "UNKNOWN" ) { } Rectangle( char const* ptr_name_, int width_ ) : width( width_ ), height( width_ ), name( ptr_name_ ) { } Rectangle( char const* ptr_name_, int width_ , int height_ ) : width( width_ ), height( height_ ), name( ptr_name_ ) { } void set_name( char const* ptr_name_ ) { name = ptr_name_; } char const* get_name() const { return name.c_str(); } void set_dimensions( int width_ , int height_ ) { width = width_; height = height_; } int area() const { return ( width * height ); } }; void normalize( Rectangle* ptr_rect ) { ptr_rect->set_dimensions( 1, 1 ); } Rectangle create_rectangle() { Rectangle temp; temp.set_name( "FACTORY CREATED" ); return temp; } int main() { Rectangle rect( "first", 333, 222 ); Rectangle rect2 = rect; // make a deep copy rect2.set_name( "second" ); std::cout << "rectangle width: " << rect.width << '\n'; std::cout << "rectangle height: " << rect.height << '\n'; std::cout << "rectangle area: " << rect.area() << '\n'; std::cout << "rectangle name: " << rect.get_name() << '\n' << '\n'; rect = rect2; // shallow assignment std::cout << "rectangle width: " << rect2.width << '\n'; std::cout << "rectangle height: " << rect2.height << '\n'; std::cout << "rectangle area: " << rect2.area() << '\n'; std::cout << "rectangle name: " << rect2.get_name() << '\n' << '\n'; rect2 = create_rectangle(); std::cout << "rectangle width: " << rect2.width << '\n'; std::cout << "rectangle height: " << rect2.height << '\n'; std::cout << "rectangle area: " << rect2.area() << '\n'; std::cout << "rectangle name: " << rect2.get_name() << '\n' << '\n'; system( "pause" ); return 0; }
<<< Correct implementation for the Rectangle | Index | >>> |