struct definition

I am used to defining a struct as follows:

1
2
3
4
5
struct Point 
{ 
    int x; 
    int y; 
}; 

with data members 'x' and 'y' where this is initialized as follows:

struct Point p1 = {0, 1};

I know these are different definitions,
But, it seems that a struct may also be defined as:

1
2
3
4
5
6
struct A
{
    A(int) { }      // converting constructor
    A(int, int) { } // converting constructor (C++11)
    operator bool() const { return true; }
};

where the latter struct is used as follows:

A a1 = 1; // copy-initialization selects A::A(int)

But, some interesting questions arise:

Where is the data member in 'struct A' ?
Is it implicitly determined (and defined) ?
If so, is this only because there is only one value stored in 'struct A' ?
Is this leaving out the data member a change due to recent C++ standards ?
Last edited on
Where is the data member in 'struct A' ?
There is none.

Is it implicitly determined (and defined) ?
No.

copy-initialization selects A::A(int)
No copy happens, just an constructor is called which does nothing.

You can define constructors with arbitrary parameters. There is no connection to a data member if you are not explicitly say so.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

struct point {
  int x, y;
  
  point(int a, int b) { //a normal constructor
    x = a;
    y = b;
  }
  
  point(int a) { //a conversion constructor with only one parameter
     x = a;
     y = a;
  }
  
  void show() {
   cout << "x=" << x << " y=" << y << endl;
  }
};

int main()
{
  
  point One(2,3); //point with normal constructor
  One.show();
  
  One = 5; //the conversion constructor was called here
  One.show();
  
  return 0;
}
Topic archived. No new replies allowed.