I need some enlightenment on const

My knowledge of C++ as it pertains to the C++ extension of C is far from pro so I'm always getting tripped up when I try to do anything beyond basics with classes.

Here is today's problem:

1
2
3
4
5
6
7
8
9
10
11

class Triangle
{
private:
	Point p[3];
	Vector normal;
	double d;
protected:
public:
	Vector getnormal() { return normal; }
};


There is obviously more to the class, but this cuts it down to the more essential. getnormal returns a copy of the triangle's normal, not a reference.

In my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct span_hit Spanner::tri_hit( const Triangle &tri, bool inout )
{
	Vector tnorm, span;
	struct span_hit span_hitpt[4];
	double dotp;

	// for an outside span, we want the first hit of the four spanner points on a triangle with a positive dot product
	// and the last hit on a triangle with a negative dot.
	// for an inside span we want the last hit on a triangle for a + dot and first hit for a - dot.

	// test for hit on the plane
	for( int i = 0; i < 4; i++ )
	{
		tnorm = tri.getnormal();   // problem here
	}
	return ;
}


This is still in development, but the problem I'm having is that because Triangle is declared const in the parameters, I can't even get a copy of the normal without VC++ express 10 telling me it's wrong. If I change the parameter to make triangle not a const, then it will work fine.

I don't understand why I can't get a copy of a const object's data member. Obviously, if I wanted to avoid modifying the object, I would declare it const, but I would also get copies of its data members when I need to use them and not references to avoid modifying the object.

So, what would be a more ideal way to do this? Declare Triangle as not const and move on or should I look at some deeper C++ mechanic?

Last edited on
closed account (3hM2Nwbp)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Triangle
{
private:
	Point p[3];
	Vector normal;
	double d;
protected:
public:
	Vector getnormal() const // <--
	{
		return normal;
	}
};


VC++ was complaining because you were calling a non-const method on a const reference. Constifying the 'getnormal' method allows it to be called from a const context.

* You'll also have to make sure that the copy-constructor of the Vector class is declared const.
Last edited on
Even though I'm getting a "copy" of the normal that will not modify the object it comes from, I still need to declare getnormal as const? Sigh, ok.

Thank you, Luc.
Const objects/references can only call const member functions. Declaring a member function as const (per Luc Lieber's example) tells the compiler "this function will not change the object".
Topic archived. No new replies allowed.