Properties declared beside the constructor - c++

I am very very new to C/C++ and not sure what the method is called. But thats why I am here trying to find the answer. let me show you an example
MyClass::MyClass() : valueOne(1), valueTwo(2)
{
//code
}
Where valueOne and valueTwo are class properties that are assigned values outside of the body, what method is this called and why is it done this way. Why not do it this way
MyClass::MyClass()
{
valueOne = 1;
valueTwo = 2
//code
}
If anyone can help me out that will be great.

That is an initializer list. You can initialize your member variables using an initializer list after the constructor.
By default the constructor will automatically create the objects that are member variables by calling their default constructors. By using an initializer list you can specify to use other constructors. Sometimes if your member variable has no constructor with no argument you have to use an initializer list.

Initialisation lists (the former style) are usually preferred for efficiency and performance reasons. Personally I prefer them for code readability reasons too since it separates simple initialisation from any complex logic in the constructor itself.

This is called an initialization list. It's done mainly for performance (with larger objects) or consistency (with built-in types like int).

It is preferred to initialize members in the initializer list. In your case it doesn't matter, but it is not possible to initialize an int& the way you did in the second code fragment. It is the only place where you can pass arguments to your base class constructor as well.

Also note, that the this pointer is accessible in the initializer list if used to reference data fields or member functions in the BASE classes only.

Related

What will happen if constructor is not used in class in c++

I am not enable to understand why constructor is used, it's functioning can be done through different method also by using "function". What constructor is able achieve in programming language that we can't achieve through function in c++. Instead if constructor we can use function also.
Main difference between constructor and function. What is the purpose of using constructor in c++
Constructor has one goal: to establish the class invariant. class is usually not just a bunch of member fields and functions: there's usually a relationship between those members that must be established and then held in order for the program to function correctly. E.g. a Rational class that consists of int n and size_t d and represents n/d should make sure that d != 0 and it can't be simplified anymore. Some class members might also be const, in which case the last point you can set the value of them (by initialization) is in the constructor.

C++ - Is it possible to use class inheritance without the member initialization list (MIL)?

I have just learned about classes in C++. I know that data members can be initialized by using the member initialization list syntax (MIL), but I think it is not very intuitive to use, and I think it is a very ugly way to assign data members.
Apparently class inheritance in C++ MUST be done through this MIL syntax. I do not understand the rationale behind this and googling did not give me answers. I am also unable to find any counter-example to this rule. Every example I saw online about inheritance requires the MIL.
So my question is: Is it possible to set up an inheritance without the MIL?
If the answer is yes, please explain how.
If the answer is no, please explain why not. (give the rationale behind mandating the MIL for inheritance)
No, that is not possible in general. If the base class has a default constructor, you can omit its initializer in the constructor of the derived class if that is appropriate. Typically though, you will want to invoke a specific constructor, and the member initializer list is the place to do that.
The reason for this is the design of the language: all "direct subobjects" of a class, meaning the base class objects and non-static data members it introduces, are actually initialized even before the body of its constructor is entered. Explicit member initializers must be given for subobjects that cannot be default-initialized, otherwise the program is ill-formed (must be rejected by compilers). For further reference, see for example cppreference on constructors and member initializer lists.
In practice this means that, while a constructor can perform additional work after initialization, constructors with empty bodies are fairly common in C++, but ones with empty member initializer lists are not.

Will using brace-init syntax change construction behavior when an initializer_list constructor is added later?

Suppose I have a class like this:
class Foo
{
public:
Foo(int something) {}
};
And I create it using this syntax:
Foo f{10};
Then later I add a new constructor:
class Foo
{
public:
Foo(int something) {}
Foo(std::initializer_list<int>) {}
};
What happens to the construction of f? My understanding is that it will no longer call the first constructor but instead now call the init list constructor. If so, this seems bad. Why are so many people recommending using the {} syntax over () for object construction when adding an initializer_list constructor later may break things silently?
I can imagine a case where I'm constructing an rvalue using {} syntax (to avoid most vexing parse) but then later someone adds an std::initializer_list constructor to that object. Now the code breaks and I can no longer construct it using an rvalue because I'd have to switch back to () syntax and that would cause most vexing parse. How would one handle this situation?
What happens to the construction of f? My understanding is that it will no longer call the first constructor but instead now call the init list constructor. If so, this seems bad. Why are so many people recommending using the {} syntax over () for object construction when adding an initializer_list constructor later may break things silently?
On one hand, it's unusual to have the initializer-list constructor and the other one both be viable. On the other hand, "universal initialization" got a bit too much hype around the C++11 standard release, and it shouldn't be used without question.
Braces work best for like aggregates and containers, so I prefer to use them when surrounding some things which will be owned/contained. On the other hand, parentheses are good for arguments which merely describe how something new will be generated.
I can imagine a case where I'm constructing an rvalue using {} syntax (to avoid most vexing parse) but then later someone adds an std::initializer_list constructor to that object. Now the code breaks and I can no longer construct it using an rvalue because I'd have to switch back to () syntax and that would cause most vexing parse. How would one handle this situation?
The MVP only happens with ambiguity between a declarator and an expression, and that only happens as long as all the constructors you're trying to call are default constructors. An empty list {} always calls the default constructor, not an initializer-list constructor with an empty list. (This means that it can be used at no risk. "Universal" value-initialization is a real thing.)
If there's any subexpression inside the braces/parens, the MVP problem is already solved.
Retrofitting classes with initializer lists in updated code is something that sounds like it will be a common thing to happen. So people start using {} syntax for existing constructors before the class is updated, and we want to automatically catch any old uses, especially those used in templates where they may be overlooked.
If I had a class like vector that took a size, then arguably using {} syntax is "wrong", but for the transition we want to catch that anyway. Constructing C c1 {val} means take some (one, in this case) values for the collection, and C c2 (arg) means use val as a descriptive piece of metadata for the class.
In order to support both uses, when the type of element happens to be compatible with the descriptive argument, code that used C c2 {arg} will change meaning. There seems to be no way around it in that case if we want to support both forms with different meanings.
So what would I do? If the compiler provides some way to issue a warning, I'd make the initializer list with one argument give a warning. That sounds tricky not to mention compiler specific, so I'd make a general template for that, if it's not already in Boost, and promote its use.
Other than containers, what other situations would have initializer list and single argument constructors with different meanings where the single argument isn't something of a very distinct type from what you'd be using with the list? For non-containers, it might suffice to notice that they won't be confused because the types are different or the list will always have multiple elements. But it's good to think about that and take additional steps if they could be confused in this manner.
For a non-container being enhanced with initializer_list features, it might be sufficient to specifically avoid designing a one-argument constructor that can be mistaken. So, the one-arg constructor would be removed in the updated class, or the initializer list would require other (possibly tag) arguments first. That is, don't do that, under penalty of pie-in-face at the code review.
Even for container-like classes, a class that's not a standard library class could impose that the one-arg constructor form is no longer available. E.g. C c3 (size); would have to be written as C c3 (size, C()); or designed to take an enumeration argument also, which is handy to specify initialized to one value vs. reserved size, so you can argue it's a feature and point out code that begins with a separate call to reserve. So again, don't do that if I can reasonably avoid it.

What is the name and reason for member variable assignment between function name and curly braces?

Look at this code snippet:
Size::Size(int iSetWidth, int iSetHeight)
:iWidth(iSetWidth),
iHeight(iSetHeight)
{
}
Supposedly, this means the same thing as:
Size::Size(int iSetWidth, int iSetHeight)
{
iWidth=iSetWidth;
iHeight=iSetHeight;
}
Why would you use the former or the latter? And what is the name of the former?
No, they don't mean exactly the same.
When a constructor is executed, before entering the code block (the code between the curly braces), it constructs all object data members. What you do in the initializers (the code after the colon and before the curly braces) is to specify which constructors to use for those members. If you don't specify a constructor for a specific data member, the default constructor will be used.
So, if you use the initialization list (first example), the right constructors will be used for each member and no additional code is necessary. If you don't, first the default constructor is used and then the code inside the curly braces is executed.
In summary:
In your first example, each member is initialised using the appropriate constructor, probably the copy constructor.
In your second example, each member is constructed using the default constructor, and then some additional code is executed to initialise it, probably the assignment operator.
EDIT: Sorry, forgot to answer your questions in the last line.
The name of the code between the colon and the curly braces is initialisation list.
If you know which is the right constructor for a variable or data member, by all means use it. This is the reason why most classes have different constructors instead of just a default constructor. So you are better off using the initialization list.
The initialisation list is almost never slower than the other technique, and can easily be faster. A well known rule when writing code is "don't optimize prematurely", but there is a not so well known counterpart: don't pessimize prematurely. If you have two options for writing a piece of code and one of them can be better than the other, but does not involve additional work or complexity, use it. In your example there is no difference, since you are using a built-in type (int). But if you were using classes, there would be a difference, so get used to the initialization list.
THe former is called initilazation lists.
You can get plentyof articles for that.
The particular reasons for using intializer lists are given here
http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/
You can refer Effective C++ to get full insight into intializer lists.
Hope it is clear.
BTW, Bjarne Stroustrup said in The C++ Programming Language that some efficiency may be gained with initialization list and he recommended us to use initialization list!

What is the reason for not allowing in C++ a default value for a variable to be a non-static method or member of a class?

I wanted to know why the default value for a variable for a method of a class, cannot be a non-static method or member of the same class.
Is there a reason for that ? Could not the compiler provide to the method the position in the class of the non-static default value ?
I tried to google quickly for an answer but I could not come up with a good answer.
EDIT: here is an example.
This is legal:
class ClassTemp
{
static int s_member;
int MagicOperation(int defaultValue = s_member)
{
return defaultValue;
}
};
But this is not:
class ClassTemp
{
int m_member;
int MagicOperation(int defaultValue = m_member)
{
return defaultValue;
}
};
Default arguments are evaluated in the context of the caller (which is why they are usually called "arguments", not "parameters"), not in the context of the class method. This means that in order to evaluate these non-static arguments the compiler would need to know the specific class instance from which to take these default values.
Of course, it is possible in theory to allow using non-static members as default parameters and make compilers use the class instance that is specified in the member call. But that does not sound like "C++ way" of doing things to me. Also, it might lead to rather convoluted and inelegant specification in some more complicated cases, for example, when the method is virtual.
The non static members are bound to a object and require 'this' pointer to access it . Since this pointer is not available for the default vaules it is not allowed
Off the top of my head, allowing default parameters from the class instance you're calling into, would require "derefing" the member value before making the call, due to function arguments getting pushed on the stack before the this pointer.
Secondly, there would be a small overhead in every call to that method utilizing the default value to the effect of:
push provided arguments...
push (this->member)
push this
These are pretty vague counter arguments, I see no reason why it can't be done either.
If I understand your question, it's because the compiler does know if the non-static variable that you are initializing this method var exists - thus the requirement that it be static so it's guaranteed to exist when the method var is initialized. It's not a matter of looking it up.