Exercise: Transform struct User Into A Class

Description

The files user.h (download) and user.cpp (download) contain declaration and definition of struct User: the structure definition, and the implementation of the constructor. The structure is written in C, in an object oriented style. Transform that struct into an equivalent C++ class.

  • Identify opportunities for C++ transformation

    • C++ brings std::string. See here for documentation.

    • The C function user_init() looks like a constructor: it initializes an object of struct User.

  • Copy both files into your work directory for transformation.

  • Use the following main program for testing (you are free to modify according to you own testing wishes).

    #include "user.h"
    #include <iostream>
    
    using namespace std;
    
    
    int main()
    {
        User joerg("Joerg Trittsicher", "Faschingbauer", 55);
    
        cout << "Firstname: " << joerg.firstname << endl;
        cout << "Lastname: " << joerg.lastname << endl;
        cout << "Age: " << joerg.age << endl;
    
        return 0;
    }
    
  • In your work directory’s CMakeLists.txt, add the following to build program user-main:

    CMakeLists.txt
    ADD_EXECUTABLE(user-main user-main.cpp user.cpp)
    

Dependencies

cluster_cxx03 C++ cluster_cxx03_standard_library_miscellanea The Standard Library: Miscellaneous Topics cluster_cxx03_data_encapsulation Data Encapsulation cluster_cxx03_exercises_userdb Exercises: User Database cluster_c The C Programming Language cluster_c_introduction Introduction cxx03_introduction Introduction c_introduction_installation Installation cxx03_introduction->c_introduction_installation cxx03_standard_library_miscellanea_string std::string cxx03_data_encapsulation_ctor_custom Custom Constructor cxx03_data_encapsulation_classes_objects Classes and Objects cxx03_data_encapsulation_ctor_custom->cxx03_data_encapsulation_classes_objects cxx03_data_encapsulation_c Object Oriented Programming In Good Ol’ C cxx03_data_encapsulation_c->cxx03_introduction cxx03_data_encapsulation_classes_objects->cxx03_introduction cxx03_data_encapsulation_classes_objects->cxx03_data_encapsulation_c cxx03_exercises_userdb_user_ctor Exercise: Transform struct User Into A Class cxx03_exercises_userdb_user_ctor->cxx03_standard_library_miscellanea_string cxx03_exercises_userdb_user_ctor->cxx03_data_encapsulation_ctor_custom