-6

Why the result of this 3? I don't underastand what "Class1() :a(3)" means.

class Class1
{
private:
    int a;
public:
    Class1() :a(3)
    {       
    };

    Class1(int f) 
    {
        a = (int)f;
    };
};

And this is Main

int main(void)
    {
        Class1 c11;
        c11.print();
    }
photeesh
  • 312
  • 5
  • 19
  • Open up any good beginner's C++ book and it'll explain what member initialiser lists are. –  Feb 08 '15 at 15:01

3 Answers3

1

"I don't underastand what Class1() :a(3) means."

It's called member initializer list, and initializes the class member variable a with the value 3.

Also see What is this weird colon-member (“ : ”) syntax in the constructor?

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

Class1() is a constructor.

A constructor is a function that initializes the values of the members of the class when an object is created. Here, when you use Class1 c11 , the constructor is called and the value c11.a is initialized as 3.

Class1() : a(3) means that the constructor is initializing a as 3.

To know more about constructors visit these links

http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

http://www.cprogramming.com/tutorial/constructor_destructor_ordering.html

Arun A S
  • 6,421
  • 4
  • 29
  • 43
0

It's a "member initializer list". Member variable int a is simply initialized with the value 3. Assigning the value to a within the constructor would be an assignment.

An initializer list initializes member variables (through the own or a parent class's constructor). If a member variable is not contained in the list, it is default-initialized, i.e. their default constructor is called, which is, for member variables of type int, an initialization with value 0.

Conclusion:

Initializing a member variable in the constructor itsself first calls the default constructor and then assigns the particular value to the member.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67