I'm learning C++, and have a question related to classes and templates. I know it's good practice to have "getters" for every variable in your class and a "setter" function. But with the code shown below, should you have a "getter" function for the array? In theory, the print function would serve the same purpose as the "getter" function would - print out everything in the array. If it is required, what would the correct code be to return that array? The array is an array of class objects.
My thinking and the code thus far:
queue.h
#pragma once
template<class T>
class Queue {
public:
Queue(int = 1);
~Queue();
void setQueue(int);
void enqueue(T);
void dequeue();
const T* getQueueArray() const;
const int getArraySize() const;
const int getArrayIndex() const;
void printQueue();
private:
T* queueArray;
int arraySize, arrayIndex;
};
queue.cpp
#include <iostream>
#include "queue.h"
template<class T>
Queue<T>::Queue(int arraySize) {
this->setQueue(arraySize);
}
template<class T>
Queue<T>::~Queue() {
delete [] this->queueArray;
}
template<class T>
void Queue<T>::setQueue(int arraySize) {
this->arraySize = arraySize;
delete [] this->queueArray;
this->queueArray = new T[arraySize];
this->arrayIndex = 0;
}
template<class T>
void Queue<T>::enqueue(T object) {
if (this->arrayIndex == this->arraySize) {
std::cout << "Rinda ir pilna, nevar pievienot elementu!\n";
}
else {
this->queueArray[this->arrayIndex] = object;
this->arrayIndex++;
}
}
template<class T>
void Queue<T>::dequeue() {
if (this->arrayIndex == 0) {
std::cout << "Rinda ir tuksa!\n";
}
else {
for (int i = 0; i < this->arraySize - 1; i++) {
this->queueArray[i] = this->queueArray[i + 1];
}
this->arrayIndex--;
}
}
template<class T>
const T* Queue<T>::getQueueArray() const {
return this->queueArray;
}
template<class T>
const int Queue<T>::getArraySize() const {
return this->arraySize;
}
template<class T>
const int Queue<T>::getArrayIndex() const {
return this->arrayIndex;
}
template<class T>
void Queue<T>::printQueue() {
for (int i = 0; i < this->arrayIndex; i++) {
std::cout << i + 1 << ". ";
this->queueArray[i].printHuman();
}
}
The array getter function works and returns a memory address. Is that behavior correct?
And I'd like to ask another question, for class print functions, which would be the better of the 2:
std::cout << "something something" << classVariable;
or
std::cout << "something something" << getClassVariable();
One way is accessing the variables directly and the other is using the "getter" functions. Does it matter and does using functions like that impact performance in a noticable way?