Search code examples
c++inheritancegetter-setter

I can't return the const char * variable using inheritance setter and getter


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. :(


Solution

  • 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