Question about struct

May 5, 2017 at 4:29am
I can't understand why I can't create a constructor in struct. Is that only available for classes?

1
2
3
4
5
6
7
8
9
10
11
  struct a{
  
  // Why does this not work?
  a(int a, int b){
   x = a;
   y = b;
  }  

  int x;
  int y;
  };
May 5, 2017 at 4:33am
Structs are classes, this does work:
http://coliru.stacked-crooked.com/a/78c22b61346703e8
Last edited on May 5, 2017 at 4:35am
May 5, 2017 at 10:08am
As mbozzi says, that should work fine. Although it would be better to use an initialiser list in the constructor, rather than assignments in the body of the constructor.

Why do you think you can't create a constructor? What problem are you seeing? Give us proper information, so that we can help you.
May 5, 2017 at 12:18pm
Are you using C or C++? C doesn't have constructors.
Topic archived. No new replies allowed.