What is the meaning of the two points on that line?

Asked

Viewed 71 times

1

The line is:

foo() : myValue1(0xDEADBEEF), myValue2(0xBABABABA) {}

I can’t understand what she does.

Here the complete code:

class foo{
public:
foo() : myValue1(0xDEADBEEF), myValue2(0xBABABABA) {}
    int myValue1;
    static int myStaticValue;
    virtual void bar() {printf("call foo::bar()\n");}
    int myValue2;
}
  • Hello. Güstavo! This is the stackoverflow in English. Please translate your question

2 answers

1


These two dots indicate a list of initialization, that is, a list of call constructors of data members of the class. For primitive data members (e.g., "int myField" in your code) in practice the effect is the same as an assignment.

See the example below for two statements by the constructor "foo" that are equivalent.

class foo {

  public:

    // #1
    // foo() : myValue1(0xDEADBEEF), myValue2(0xBABABABA) {}

    // #2
    foo() {
      myValue1 = 0xDEADBEEF;
      myValue2 = 0xBABABABA;
    }

    int myValue1;
    static int myStaticValue;
    virtual void bar() {printf("call foo::bar()\n");}
    int myValue2;
}

When data members are instances of another class, however, the use of the initialization list is the only way to initialize these members.

See the example below.

class A
{
  public:
  A(int x, int y)
  {
    // faz alguma coisa com x e y
  }
}

class B
{
  public:

  B(int i, int j) : a(i, j)
  {
    // ...
  }

  A a;
}

0

This line:

foo() : myValue1(0xDEADBEEF), myValue2(0xBABABABA) {}

It means that the values myValue1 and myValue2 are being initiated with the values 0xDEADBEEF and 0xBABABABA, respectively. This constructor is called Member Initialization.

Just to better understand, the above code is similar (not equal) to the type constructor Member Assignment, that in the same example would be:

foo()
{
   myValue1 = 0xDEADBEEF;
   myValue2 = 0xBABABABA;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.