Clarify a couple of things in and example code

Hey guys!
I'm a total beginner in C++ but I have a pretty strong background in ActionScript 3, Java and PHP, so I only need to clarify a couple of C++ things which are not present in those languages I mentioned

So, here's the code
1
2
3
4
5
6
7
class A {
	int a;
	
public :
	A (const int &a) : a(a) { }
	const int & value() const { return a; }
}  

Well, of course I understand that this is a class declaration whose constructor
takes a constant reference to some integer value. But what comes next makes me a bit confused.
What does this code: : a(a) { } mean exactly?

And this one: const int & value() const { return a; }

p.s. This one is from lynda.com tuts, "operators overloading" explanation, but there's no explanation of this code itself
Last edited on
I'll rewrite the function for you.
1
2
3
4
A::A(const int &a)
 : a(a)
{
}
This is a constructor for class A that take an int by const reference as you said. : a(a) is an initializer. The first a is the member a in the class, the second a is the parameter a.

The function body is empty.

Let's change your example a little.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class B
{
	std::string s;

public:
	B(const std::string& str) :
		s(str)
	{
	}
	B(const std::string& str, int num)
	{
		s = str;
	}
};
Here we have two constructors. I've used an overload to distinguish them, but they demonstrate two different ways of initialising member s.

The first constructor that uses an initialiser list calls the copy constructor on std::string.

The second constructor calls the default constructor on std::string to intialize s, then it calls the assignment operator to copy the content of str into s.

I hope you can see that the first constructor is more efficient.
Last edited on
Thank you very much :)

After your second example it turned out a lot more clear to me. Actually a(a) was confusing, I guess they (lynda's instructors) should have better used some more informative property names for tutorials.
Yeah, this way of initializing properties looks very unfamiliar to me, I gotta definitely spend some time to get used to things like that
Topic archived. No new replies allowed.