1

Recently while going through someone code written in C++, I saw that he declares the function in very different way, The function he defines is shown below:

struct Node{
   Node* next;
   Node* prev;
   int value;
   int key;
   Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
   Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
};

So in this code

Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};

I am not able to understand this line, like how he defines the function in this way because we define function having return type,arguments and then body(In case of constructors we don't have return type). I am not able to understand how this line of code works. Please anyone explain me this in detailed.

In this code I am not able to understand how he uses the constructor like he defines it using colon: and also see how he initialize the variable value just convert it to a function without having body value(val){} Thanks in advance.

  • 1
    Are you familiar with `classes`? A struct and a class are pretty much the same thing (except for default `private`/`public` access to members). This function `Node(...)` is just the constructor for an object of type `Node`. – JohnFilleau Feb 20 '20 at 16:49
  • It is `Node` constructor with initializers, search and read about it – mvidelgauz Feb 20 '20 at 16:50
  • Its a constructor but it defines it with a colon, We use brackets for this and also see how he initialize the varible value, He just convert it to a function without body. –  Feb 20 '20 at 16:52
  • @VinayKShukla "_He just convert it to a function without body._" But the constructor in your example has a body: `{}`. It's just that it's empty. You can't use constructor initializer list on a declaration. Note: The semi-colon after the body isn't needed. – Algirdas Preidžius Feb 20 '20 at 16:57

0 Answers0