How to return a struct from a function in C++?

135,702

Solution 1

You have a scope problem. Define the struct before the function, not inside it.

Solution 2

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

Solution 3

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

Solution 4

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;
Share:
135,702
tail_recursion
Author by

tail_recursion

Updated on February 19, 2020

Comments

  • tail_recursion
    tail_recursion about 4 years

    I've tried on a few different forums and can't seem to get a straight answer, how can I make this function return the struct? If I try 'return newStudent;' I get the error 'No suitable user-defined conversion from studentType to studentType exists.'

    // Input function
    studentType newStudent()
    {   
        struct studentType
        {
            string studentID;
            string firstName;
            string lastName;
            string subjectName;
            string courseGrade;
    
            int arrayMarks[4];
    
            double avgMarks;
    
        } newStudent;
    
        cout << "\nPlease enter student information:\n";
    
        cout << "\nFirst Name: ";
        cin >> newStudent.firstName;
    
        cout << "\nLast Name: ";
        cin >> newStudent.lastName;
    
        cout << "\nStudent ID: ";
        cin >> newStudent.studentID;
    
        cout << "\nSubject Name: ";
        cin >> newStudent.subjectName;
    
        for (int i = 0; i < NO_OF_TEST; i++)
        {   cout << "\nTest " << i+1 << " mark: ";
            cin >> newStudent.arrayMarks[i];
        }
    
        newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
        newStudent.courseGrade = calculate_grade (newStudent.avgMarks);
    
    }
    
  • Zac Howland
    Zac Howland over 10 years
    If he creates an automatic studentType and returns it by copy, the copy constructor will be called (a default one is created if you don't create one), so he will not have any issues. Declaring the structure inside the function is his primary problem - and there is no need to declare it dynamically at present.
  • Ramesh-X
    Ramesh-X over 6 years
    as you are not using new operator to create the structure instance, will it be deleted automatically after you call newStudent()
  • Javier Cabero
    Javier Cabero over 5 years
    Isn't it more efficient to prevent the copy constructor by using a pointer?
  • Sandburg
    Sandburg about 5 years
    @JavierCabero I think there will be a copy-elision automatically... so no copy at all! But if you really want to manage that, you can implement some lvalue move on the struct object.
  • Little Helper
    Little Helper about 4 years
    Isn't it bad to return a variable that has been allocated on the stack?
  • rkgghz
    rkgghz almost 4 years
    @LittleHelper: That would only be a problem if you return by reference.
  • cuddlebugCuller
    cuddlebugCuller over 3 years
    @Ramesh-X No, because new creates a pointer to an instance created on the heap. If you return the structure directly, it just "copies" (a sufficiently intelligent compiler may just use the location that the caller provided for the returned struct) the bits of the structure into the lvalue that the result of the function call was assigned to in the caller. The problem with returning a local structure arises when you return a "pointer" (the pointer may be a reference, which is not actually required to be implemented using pointers) to the local structure.
  • cuddlebugCuller
    cuddlebugCuller over 3 years
    @ZacHowland AIUI, the default method for returning something from a function is by move, not by copy. The callee doesn't need it anymore, after all.
  • Zac Howland
    Zac Howland over 3 years
    @cuddlebugCuller When the comment was made, that was not the case :) The move semantics have been added and updated a couple times since 2013.