The C++ & operator

I am having problems figuring out the use of the & operator I think I understand how to use it as a reference pointer. But when using it after the variable I do not have a clue of whats going on. here is some example code of how T& is used. Below is a class template for a stack. I dont understand T& I do understand &T what is the difference in T& and &T I would appreciate your help

template < class T >
class Stack {
public:
Stack( int = 10 ); // default constructor stack size 10
~Stack() { delete [] stackPtr; } // destructor
bool push( const T& ); //push an element onto stack
bool pop( T& ); // pop an element off stack
private:
int size; // # of elements in stack
int top; // location of top element
T *stackPtr; // pointer to stack

bool isEmpty() const { return top == -1;} // utility
bool isFull() const { return top == size -1;} // functions
};
Last edited on
In this context & is not an operator, It is a designation of a reference that is an alias of a variable.

Consider

1
2
3
4
5
6
int x = 10;

int & rx = x;

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


In your code it means that arguments are passed by referecnce that is no copy of an object will be created.
Topic archived. No new replies allowed.