Classes and const member functions

I have two classes called Point and Triangle.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Point
{
    

public:

    double x;
    double y;

Point(double a, double b): x(a), y(b) {
 
};

class Triangle
{
public:

  Point a, b, c;
    
    Triangle():a(0,0),b(0,0),c(0,0){} 
    
    Triangle(Point i1,Point i2, Point i3) :a(i1), b(i2), c(i3){}


// Translation of triangle
    
    Triangle translated (const Point &w) const {
    
    Point a1 = a + w;
    Point b1 = b + w;
    Point c1 = c + w; 
    return Triangle (a1, b1, c1);
    
    }

Triangle rotated (const double angle) {
   
   Triangle r;
   
   r.a = a.rotated(angle);
   r.b = b.rotated(angle);
   r.c = c.rotated(angle);
     
   return r;
   }

};


If I change the second function to this it throws an error.

CaseB:

1
2
3
4
5
6
7
8
9
10
11

Triangle rotated (const double angle) {
   
   Triangle r;
   
   r.a = a.rotated(angle);
   r.b = b.rotated(angle);
   r.c = c.rotated(angle);
     
   return r;
   }


Why does the first function work fine with the cons but fail in the second function (as in case B)? Does declaring an empty Triangle r have anything to do with it?






Last edited on
> Why does the first function work fine with the const but fail in the second function

Probably because Point::rotated() is not const-qualified.

With everything const-correct:
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
struct point
{
    explicit point( double a = 0, double b = 0 ) : x(a), y(b) {}

    point rotated( double angle ) const ;
    point operator+ ( const point& ) const ;
    // etc.

    double x, y ;
};

struct triangle
{
    point a, b, c;

    triangle() = default ;
    triangle( point i1, point i2, point i3 ) : a(i1), b(i2), c(i3) {}


    triangle translated( const point &w ) const {
        return { a+w, b+w, c+w } ;
    }

    triangle rotated( double angle ) const {
        return { a.rotated(angle), b.rotated(angle), c.rotated(angle) } ;
    }
};

http://coliru.stacked-crooked.com/a/14c8f72610238be0
Last edited on
Thank you, that solved the problem. My rotated function in Point class was indeed not set to const.
Topic archived. No new replies allowed.