-1

I've just started learning c++ these past couple of months, and there's so much I haven't been exposed to. I've tried searching for this syntax, but with no success. It's from an exercise on programmr.com which concerns classes and operator overloading. Here's the code:

class temp
{
  int value;

public:
  temp(int v=0) : value(v) { }

I understand it's declaring a class called "temp", with a private member variable "value". I'm guessing the code under "public" is declaring a default constructor. I'm used to seeing default constructors declared in function syntax:

temp (int v=0){
      value = v;
     some expressions;
}

The part I'm confused about is after the colon:

: value(v) {}

What is the function of the colon there, exactly? What is the relationship between the default constructor and "value(v) {}"? Is this just a different syntax of the function-style default constructor I gave an example of above? Thanks for helping out this total n00b!

Huaidan
  • 109
  • 1
  • also see answers to http://stackoverflow.com/questions/4589237/c-initialization-lists – Andrey Sidorov Jan 20 '14 at 06:13
  • It's called initialization list - it allows you to call constructors of member objects before executing instructions in brackets. In C++ primitives got constructors as well - they just initiate variable with whatever value you pass inside. – Mateusz Kubuszok Jan 20 '14 at 06:18
  • Thanks all to providing the terminology "initialization list". Now that I know that, I can see that's in Chapter 10 section 1. I'm still on chapter 9 section 2! Thank you so much! – Huaidan Jan 20 '14 at 06:25

1 Answers1

1

This is an another way to initialize the class member variable.

: value(v)

this will simply work like

value = v;

there is no difference between these two declaration.

if suppose you need to initialize more then one variable then you can try like this..

:value1(v1), value2(v2), value3(v3)

this is very common initializing pattern.

Note that you have to use this pattern if the data member that you're initialising is marked const.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Ravindra Gupta
  • 568
  • 3
  • 8
  • 18