Home > OS >  Getting private variables in a child to a parent?
Getting private variables in a child to a parent?

Time:12-06

I recently had a test on class inheritance and one of the questions required me to write a program that had a function in the parent class that required a private variable from the child class to work. This is what the question asked:

"Write a program that consists of two classes. A parent class, Human, and a child class, Student. (You may use a different human if needed, IE : ‘Baby’ class instead of ‘Student) Create a public inheritance connection between both classes.

The parent class should have the following member functions PUBLIC sleep() - prints a message about the hours slept and quits program

The child class have the following members functions and variables : PUBLIC setHoursSlept() - lets user input amount of hours slept. PRIVATE getHoursSlept() - returns amount of hours sleep. PRIVATE hoursSlept - variable that accepts the amount of hours slept."

I had no idea how to make hoursSlept accessable from the parent class So here is what I submitted


#include <iostream>
using namespace std;

class Human{


public:
  //taking the L on this one
  //defaults hours slept to 0
  int hoursSlept=0;
//ends the program
void sleep(){
  cout << "I slept " << hoursSlept << " hours" << endl;
  exit(0);
}
};   
//make a child class of human with a public connection called student
class Student: public Human{
  public:
  void setHoursSlept(){
    cout << "enter hours slept" << endl;
    cin >> hoursSlept;
  }
  private:
  int getHoursSlept(){
    return hoursSlept;
  }
};

int main() {
  //make new student
  Student test;
  //set hours slept
  test.setHoursSlept();
  //sleep
  test.sleep();

}

CodePudding user response:

I think the composer of the test <expletive deleted>ed up. There are ways to hack around the protections built into C , but they tend to be brittle. Here's one hack that's not brittle and takes advantage of the fact that the accessibility of a function takes no part in the resolution of overrides.

#include <iostream>
using namespace std;

class Human
{
public:
    virtual int getHoursSlept() = 0; // can now call getHoursSlept in derived classes
                                     // regardless of accessibility
    void sleep()
    {
        cout << "I slept " << getHoursSlept() << " hours" << endl;
        exit(0);
    }
};
class Student: public Human
{
    int hoursSlept = 0;
public:
    void setHoursSlept()
    {
        cout << "enter hours slept" << endl;
        cin >> hoursSlept;
    }
private:
    int getHoursSlept() override
    {
        return hoursSlept;
    }
};

int main()
{
    //make new student
    Student test;
    //set hours slept
    test.setHoursSlept();
    //sleep
    test.sleep();
    
}

See the code in action!

  •  Tags:  
  • c
  • Related