Exercise: Transform struct User Into A Class


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:

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


cluster_cxx03 C++ 03 cluster_cxx03_exercises_userdb Exercises: User Database cluster_cxx03_standard_library_miscellanea The Standard Library: Miscellaneous Topics cluster_cxx03_data_encapsulation Data Encapsulation cluster_c The C Programming Language cluster_c_introduction Introduction cxx03_introduction Introduction c_introduction_installation Installation cxx03_introduction->c_introduction_installation cxx03_exercises_userdb_user_ctor Exercise: Transform struct User Into A Class cxx03_standard_library_miscellanea_string std::string cxx03_exercises_userdb_user_ctor->cxx03_standard_library_miscellanea_string cxx03_data_encapsulation_ctor_basics Constructor: Basics cxx03_exercises_userdb_user_ctor->cxx03_data_encapsulation_ctor_basics cxx03_data_encapsulation_introduction Introduction: Classes and Objects cxx03_data_encapsulation_ctor_basics->cxx03_data_encapsulation_introduction cxx03_data_encapsulation_introduction->cxx03_introduction