I was learning about structures in C++. I had a question:

1.struct integer 
2.{
3.    int i;
4.    integer (int j = 0) : i (j) {};
5.    integer operator* (const integer &k) const 
6.    {
7.        return integer (i + k.i);
8.   }
9.};

In the above code, i was not able to understand the :i(j) in line 4 and const which is at the end of line 5. What does these mean?

Recommended Answers

All 3 Replies

maybe you are using a C compiler instead of C++

I am using a C++ compiler. That is not an issue.
I wanted to understand the declarations done inside the structure.

> i was not able to understand the :i(j) in line 4
It initialises i (you member variable) with j (the parameter).

Compare with integer (int j = 0) { i = j; }; which is an assignment.
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

> const which is at the end of line 5. What does these mean?
It means that the function will not modify the internal state of the class.
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.