1

I can print the correct value in setter function but when I try to return the same variable using getter there is no output. Here is my code. Anyone has idea on how I correct my code?

class Student {
public:
    char age;
    double height;
    double gpa;

    int getAge();
    void setAge(int *);
protected:
    const char * name;
 };

class Male :Student {
 public:
 void setName(const char * s);
 const char * getName();
};

void Male::setName(const char * s){
const char* name = s;
std::cout << name << std::endl;
}

const char* Male::getName() {
 return name; //I can't return the value of variable name.
 std::cout << name << std::endl;
}

 void Student::setAge(int* c) {
 age = *c;
}

int Student::getAge() {
 return age;
}

int main() {
 Student jason;
 Male myName;
 int edad = 30;
 jason.height = 162;
 jason.gpa = 1.5;

 jason.setAge(&edad);
 myName.setName("James");

std::cout << jason.height << "\n" << jason.getAge() << "\n" << jason.gpa << "\n" << std::endl;
system("pause");
return 0;
}

I don't know why I can't return the const char variable. :(

  • 1
    Use public inheritance: ``class Male : public Student {`` – Asesh Apr 26 '18 at 04:05
  • Where do you set the name? – Tas Apr 26 '18 at 04:07
  • If your text-book doesn't cover this (highly unlikely) then [here's a list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). Get one or two beginners book from the list, and start reading *from the beginning*. – Some programmer dude Apr 26 '18 at 04:08
  • @Tas I set the name in setName function. –  Apr 26 '18 at 04:10
  • 1
    Firstly, use `public` inheritance, if you expect users of the derived class to call members the derived class inherits from base classes. Second, your `setName()` creates an object named `name` that has NO RELATIONSHIP WHATSOEVER to the member named `name` in the class, and ceases to exist when the function returns. – Peter Apr 26 '18 at 04:10
  • @Asesh still the return value is still error reading character. :( –  Apr 26 '18 at 04:10
  • @Peter I need to use protected because i'm using inheritance. You're right I should not create another local variable. I should connect it to my base class. –  Apr 26 '18 at 04:21
  • @Someprogrammerdude thanks for the info dude. It'll help me. :) –  Apr 26 '18 at 04:25

1 Answers1

0
void Male::setName(const char * s) {
  name = s;
  std::cout << name << std::endl;
}

You need to set s to the member variable name instead of creating a local variable in the method

mammothb
  • 16
  • 5