Syntax inside a struct that looks like a function

Asked

Viewed 45 times

1

I was analyzing a code in C++ and came across the following structure:

struct ligacao {
  int v_;
  int w_;
  int ComEXp; 
  ligacao(int v, int w, int ComEXp1) : v_(v), w_(w), ComEXp(ComEXp1) {} // Minha duvida seria concretamente aqui
};

What use is the 4th line of this stretch?

1 answer

2


This is a constructor method. Don’t know what it is? Has answer about: What good is a builder?.

So this code will be executed when creating an instantiated object from this structure. Péra, which code? Yeah, there’s a code there, though in a different way.

The initialization is done directly without needing to assign the values in the body of the method. This is guaranteed that the initialization is done before the body, is done inplace without intermediaries and that always occurs, without risks of someone deleting or changing the semantics inadvertently when tampering with the body code. This can be seen in more detail in What is the difference between initializing a variable in these constructs? And how to default a constructor? and What is the difference between initializing a constructor or assigning within the constructor?.

The documentation of this is in https://en.cppreference.com/w/cpp/language/constructor.

Browser other questions tagged

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