Usage of reference operator

When something like the below is done, what does it mean?

1
2
  const sf::Texture& texture=font.getTexture(); 
  //font is type sf::Font, and sf::Font::getTexture() returns const sf::Texture& 

Talking about the usage of the & operator in "sf::Texture&"


Aceix.
Last edited on
Oh, I am sorry.

It means that a const reference is created that will reference the object returned by the function.:)

Consider the example

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

int main()
{
	struct A
	{
	private:
		int x;
	public:
		A( int i = 0 ) : x( i ) {}
		A & operator ++()
		{
			++x;
			return ( *this );
		}
		const int & getX() const { return ( x ); }
	} a = 10;

	const int &x = a.getX();

	std::cout << "x = " << x << std::endl;

	++a;

	std::cout << "x = " << x << std::endl;

	++a;

	std::cout << "x = " << x << std::endl;

	// Do not do this.:)
	int &x2 = const_cast<int &>( a.getX() );

	++x2;

	std::cout << "x = " << x << std::endl;
}

Last edited on
Thanks, so is it always necessary to have a constant reference variable, or one can have a variable one?
eg:
1
2
 int &f=a.getX();
//in this case getX() returns int& 


Aceix.
If the function returns a const reference then you shoud also use a const reference. Otherwise you may declare a non-const reference.
For example std::vector's operator [] is overloaded to return either a const reference or non-const reference.
Last edited on
Thank you very much for the information.

Aceix.
Talking about the usage of the & operator in "sf::Texture&"

In this context, & is not an operator. It's a declarator -- the "reference declarator".

cf.

1
2
3
int value = 3;

int* ptest = &value;


Here & is an operator : the address-of operator

Same deal for the indirection operator and pointer declarator, which are both *.

Andy
Last edited on
Topic archived. No new replies allowed.