0

Everything in my coding works except the get and set name functions. When I call getName, it prints blank. I've tried a few different solutions, but the only thing that has worked is actually saving the fullName string inside of main, and calling it from there. It's almost as if it's not letting me call the variables because they are private.

Here is my .cpp file.

#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>

#include "Student.h"

using namespace std;

int main()
{
    //for student name
    string firstName;
    string lastName;
    string fullName;


//student name

cout << "Please enter your students first name" << endl;
cin >> firstName;
cout << "firstName = " << firstName << endl;


cout << "Please enter your students last name" << endl;
cin >> lastName;
cout << "lastName = " << lastName << endl;

aStudent.setName(firstName, lastName);
fullName = aStudent.getName();

cout << "Your students name is : ";
cout << fullName << endl;

}
#endif

Here are my functions, and class, .h file.

#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
class Student
{

private:
string fName;
string lName; 

public:
string getName();
void setName(string firstName, string lastName);

};

string Student::getName()
{
return fName + " " + lName;
}
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName;
lastName = lName;
}
1
  • Your code structure is messy, the header file should only have the method declarations.
    – nikhil
    Aug 12, 2012 at 7:29

2 Answers 2

8
void Student::setName(std::string firstName, std::string lastName)
{
    firstName = fName;
    lastName = lName;
}

Surely you see the problem there. Hint, assignment copies the thing on the right to the thing on the left.

1
  • wow, i definitely spent too much time looking at the full program to miss something like that. Thanks blushes, so embarrassing! Aug 13, 2012 at 12:41
2
void Student::setName(std::string firstName, std::string lastName)
{
    firstName = fName; // you're assigning the local firstName to your class instance's
    lastName = lName;  // variable; reverse this and try again
}

// ...
void Student::setName(std::string firstName, std::string lastName)
{
    fName = firstName;
    lName = lastName;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.