When using this, what exactly can one do with it? Has this to do with inheritance of some sort? Meaning that whatever is following the : is then made available to the class itself (because the access specifier is private), or - if public, anywhere this header file is included? If so, how would this be used?
This syntax is to do with inheritance. Everything to the right of that, the class can inherit behaviour from. The access modifier works in exactly the same way as they do for variables and functions. Private: Can only be accessed by functions and operators in this class. Protected: The above, and can also be accessed by any functions and operators in a class that inherits from this class. Public: The above, and can also be accessed from anywhere that includes this header, or from an instance if the function is not static.
C++ Has some very interesting behaviour with multiple inheritance when their's a common ancestor though which you'll need to look into in order to prevent any unexpected behaviour when utilising it. If all the classes you're inheriting from do not share a common ancestor (or you're only inheriting from one class) then it's quite strait forward to work with.
#include <iostream>
struct Foo {
int x = 7;
};
struct Bar : public Foo {
int x = 42;
};
int main()
{
Bar bar;
std::cout << bar.x << ' ' << bar.Foo::x;
}
#include <iostream>
usingnamespace std;
class Happy
{
public:
string mood = "On cloud nine";
};
class Sad
{
public:
string mood = "Down in the dumps";
};
class Today : public Happy, public Sad
{
};
int main()
{
Today Tuesday;
cout << Tuesday.mood;
}
which elicits
class.cpp: In function 'int main()':
class.cpp:27:20: error: request for member 'mood' is ambiguous
cout << Tuesday.mood;
^~~~
class.cpp:15:18: note: candidates are: std::__cxx11::string Sad::mood
string mood = "Down in the dumps";
^~~~~~~~~~~~~~~~~~~
class.cpp:8:18: note: std::__cxx11::string Happy::mood
string mood = "On cloud nine";
^~~~~~~~~~~~~~~
First of all thank you, TheBeardedQuack, keskiverto, and lastchance (for the umpteenth time since whenever I tried posting this there was a problem ...)
TheBeardedQuack, thank you for the thorough explanation!
keskiverto, your link pointed me in the right direction, so thanks for it!
lastchance, it is deprecated but does still work. It was useful and only used for the testing purposes which was to write function objects.
The only question that remains is whether it is such a good idea to inherit directly from classes such as string etc. But from what I found it has its uses and isn't uncommon to do it.