I am a beginner in C++ and am trying to learn it by looking at examples.
Here is an example definition for a class that I don’t understand the meaning completely:
class MyClass{
public:
std::string name;
void *data;
MyClass(const std::string& t_name, void *t_data) : name(t_name), data(t_data) {}
};
Here is what I understand:
name and *data are variables of the class and, MyClass(…) is the constructor. The meaning of : is the left side class is derived from the right hand side class. However, what is the meaning of this part of the code:
MyClass(const std::string& t_name, void *t_data) : name(t_name), data(t_data) {}
Here are the questions:
- what are “t_data” and “t_name”? Are they initial values for “data” and “name”? what is the reason t_ is used here?
- what is the meaning of : in the above line?
- what is {} at the end of that line?
Thanks for the help.
TJ
They are the arguments passed to the constructor. If an object were created as
then, in the constructor,
t_namehas the value"Fred"andt_datahas the value ofsome_pointer.Some people like to tag the arguments to give them different names to the class members, but there’s no need to do that unless you want to.
That marks the start of the initialiser list, which initialises the class member variables. The following initialisers,
name(t_name), data(t_data)initialise those members with the constructor’s arguments.That’s the constructor’s body, like a function body. Any code in their will be run after the members have been initialised. In this case, there’s nothing else to do, so the body is empty.