struct function with const

How do I return multiple elements through a function with const?

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
#include <iostream>
#include <cmath>

struct points {
double x = 0;
double y = 0;

points midpt() const {
points a;

a.x = x / 2;
a.y = y / 2;

return /** what do I put here so it returns and creates a new point that is this point's midpoint */
}
};

int main() {
points a{3, 7};
a.midpt();

std::cout << "midpoint = " << a.x << ", " << a.y << std::endl;
}

// this just returns "midpoint = 3, 7" 
Last edited on
1
2
points mp = a.midpt();
std::cout << "midpoint = " << mp.x << ", " << mp.y << std::endl;
I'm trying to make it so the function returns and creates a new point that is this point's midpoint so I don't have to create a new point in the main function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

struct point {

    double x = 0 ;
    double y = 0 ;

    point mid() const { return point{ x/2, y/2 } ; }
};

int main() {

    const point a { 3, 7 } ;

    const point b = a.mid() ;
    std::cout << b.x << ", " << b.y << '\n' ;
}
is it possible to do line 15 within the function point mid() const;
and not in the main function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

struct point {

    double x = 0 ;
    double y = 0 ;

    point find_mid() const { return point{ x/2, y/2 } ; }

    void print_mid() const {

        const point b = find_mid() ;
        std::cout << b.x << ", " << b.y << '\n' ;
    }
};

int main() {

    const point a { 3, 7 } ;
    a.print_mid() ;
}
I mean like is there a way to get the Point so I can plug it back in to get the mid point of the mid point without cout just so it returns the points but as a new point
> can plug it back in to get the mid point of the mid point

We can use the result of the function anonymously. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

struct point {

    double x = 0 ;
    double y = 0 ;

    point mid() const { return point{ x/2, y/2 } ; }
};

int main() {

    const point a { 3, 7 } ;

    // get the mid point of the mid point
    const point b = a.mid().mid() ;
    std::cout << "mid point of mid point: " << b.x << ", " << b.y << '\n' ;

    // get the mid point of the mid point of the midpoint
    const auto c = a.mid().mid().mid() ;
    std::cout << "mid point of mid point of mid point: " << c.x << ", " << c.y << '\n' ;
}
Topic archived. No new replies allowed.