From 62e2ec9c7e6dc692e217709d6b6d9adbd72865a7 Mon Sep 17 00:00:00 2001 From: tobiglaser <76131623+tobiglaser@users.noreply.github.com> Date: Fri, 6 May 2022 00:00:18 +0200 Subject: [PATCH] adding static vs member demo --- CMakeLists.txt | 5 +++++ src/class-member-variables.cpp | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/class-member-variables.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 488803a..a2eb145 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,11 @@ src/testCommandList.cpp target_include_directories("Info3_Praktikum-test" PUBLIC include/) +add_executable("Class-Member-Variable-demo" +src/class-member-variables.cpp +) + + # Doxygen documentation find_package(Doxygen) if (DOXYGEN_FOUND) diff --git a/src/class-member-variables.cpp b/src/class-member-variables.cpp new file mode 100644 index 0000000..790a705 --- /dev/null +++ b/src/class-member-variables.cpp @@ -0,0 +1,34 @@ +#include <iostream> + +using std::cout; +using std::string; + +class ControlDeveloper +{ +private: + // class variable + // explicit "inline" to initialize in this translatin unit + inline static string CD_Class = "CLASS Control-Developer"; + // member variable + const string CD_Member = "MEMBER Control-Developer"; +public: + // declare static to be called without object + static string getCDClass() { return CD_Class; } + // regular getter + string getCDMember() { return CD_Member; } +}; + + +main() +{ + cout << "Demonstration of class vs. member variables:\n"; + cout << "Without constructing an object we can call the static getter from the CD namespace:\n"; + cout << "CD_Class: " << ControlDeveloper::getCDClass() << '\n'; + cout << "To be able to get the member variable we need to construct"; + cout << " an object as the value will be specifically created for every object.\n"; + ControlDeveloper cd = ControlDeveloper(); + cout << "We can now call the non static getter:\n"; + cout << "CD_Member: " << cd.getCDMember() << '\n'; + cout << "We can now also use the object to call the static getter (with the same effect):\n"; + cout << "CD_Class: " << cd.getCDClass() << '\n'; +} \ No newline at end of file -- GitLab