I’d suggest reading a C++11 book if you want to learn those concepts, the for loop right below is what’s called a range-based for loop; it makes use of iterators provided by your container class. A book I’d recommend is the C++ programming language that focuses on C++11, first a few examples. Let’s say you create an std::vector to store the first 9 natural numbers, let’s say you want to loop through this vector and see what it contains by printing out each element, but instead you want to make use of the new range-based for loop. You’d do it like so, the auto keyword is a new feature - basically auto deduction during compile time so you don’t have to figure out what i is, very useful for lambdas and such.
int main()
{
std::vector<int> NaturalNumbers{1,2,3,4,5,6,7,8,9};
for (auto i : NaturalNumbers){
std::cout << i << std::endl;
}
}
Now note that I didn’t use an ampersand because I only needed a copy of the elements, on the other hand if you need a reference then you’ll want to use an ampersand.
To see the difference, try this out.
int main()
{
std::vector<int> NaturalNumbers{1,2,3,4,5,6,7,8,9};
for (auto i : NaturalNumbers){
i = 1;
std::cout << i << std::endl;
}
std::cout << std::endl;
for (auto i : NaturalNumbers){
std::cout << i << std::endl;
}
}
int main()
{
std::vector<int> NaturalNumbers{1,2,3,4,5,6,7,8,9};
for (auto &i : NaturalNumbers){
i = 1;
std::cout << i << std::endl;
}
std::cout << std::endl;
for (auto i : NaturalNumbers){
std::cout << i << std::endl;
}
}
In the last version, the elements in the container gets modified as it is accessed by reference and not by value. Just remember that to make use of this feature, your class should implement the begin() and end() member functions.
As for the last question, this is essentially constructing and assignment values to members of the class, I’d advice using an initialization list than assignment in the constructor of your class for performance.