Printing private class array data

I want to get data from an objects array and print it using "cout". Having trouble figuring out how to implement this. I have an array of pointers "classRosterArray" that point to student objects. I must use the "GetCourseDays()" method to get the data as the "courseDays[]" variable is private to the Student class.

Student.cpp
1
2
3
  int Student::GetCourseDays() {
	return courseDays[0], courseDays[1], courseDays[2];
}


Main function call
 
cout << classRosterArray->GetCourseDays();
You can't return multiple things from a function. That isn't what the comma operator does.
I think you're over-restricting yourself here.
You can have the class itself handle printing to a stream:
1
2
3
4
5
std::ostream& Student::PrintCourseDays(std::ostream& os)
{
    os << courseDays[0] << ' ' << courseDays[1] << ' ' << courseDays[2];
    return os;
}

called like:
classRosterArray->PrintCourseDays(cout) << '\n';

(Why is your Student object called a 'classRosterArray'. That doesn't make sense to me.)

Alternatively, if you know the size of the array is 3, you could just return a pointer to the array, and expect that the user knows how to handle it.

1
2
3
int* Student::GetCourseDays() {
	return courseDays;
}


1
2
int* days = classRosterArray->GetCourseDays();
cout << days[0] << ' ' << days[1] << ' ' << days[2] << '\n';

Last edited on
To return more than 1 value from a function, consider using a tuple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <tuple>

auto ret3()
{
	int arr[3] {1, 2, 3};

	return std::tuple{arr[0], arr[1], arr[2]};
}

int main()
{
	const auto [a, b, c] {ret3()};

	std::cout << a << ' ' << b << ' ' << c << '\n';
}


Last edited on
> Why is your Student object called a 'classRosterArray'. That doesn't make sense to me
ah, but it is not an object, you see, but a pointer
although that only gives more questions.
Topic archived. No new replies allowed.