-2

Before doing a C++ class, I decided to first do it in Python.

There were good sources to do the Python class but I couldn't find useful sources for C++.

Python code:

class Human:
    def __init__(self, first, last, age, sex):
        self.firstname = first
        self.lastname = last
        self.age = age
        self.sex = sex
    ...
class Student(Human):
    def __init__(self, first, last, age, sex, school, semester):
        super().__init__(first, last, age, sex)
        self.school = school
        self.semester = semester
    ...

C++ code:

class Human {
protected:
    string name;
    string lastname;
    int age;
    string sex;
public:
    Human(string name, string lastname, int age, string sex):
    name(name), lastname(lastname), age(age), sex(sex){
    }
    ~Human();
};
class Student: protected Human{
public:
    string school;
    int semester;
    //Student(string school, int semester);
    ~Student();
};

how can I do the same thing in my C++ code?

Miguel Yurivilca
  • 375
  • 5
  • 12
  • 1
    What is your question? Please read [ask]. – ChrisGPT was on strike Apr 24 '18 at 22:33
  • You've obviously got some Python code and some C++ code. In what way is the C++ code not meeting your needs? Again, please read [ask]. – ChrisGPT was on strike Apr 24 '18 at 22:51
  • What is it about the python code that you want to emulate in c++ and how does this c++ code not meet those requirements?. It's just straight inheritance. Why does it need to be protected in c++? The python classes expose those members as public (I'll assume thats the case as they dont have a leading underscore). – Paul Rooney Apr 25 '18 at 00:52

1 Answers1

1

You can call the super constructor and initialize class variables in C++ using an initializer list.

As a simplified example:

class Human {
   int age;
   string name;
 public:
    Human(string name, int age) : age(age), name(name) {} // initializer list
};

class Student : public Human {
    string school;
 public:
    Student(string name, int age, string school)
        : Human(name, age), school(school) {}  // initializer list
}

The Human(name, age) part of the student constructor calls the constructor in the base Human class.

Your commented out Student(string school, int semester) constructor wouldn't be able to properly initialize the Human base class as it doesn't contain any information about a Human (name, age, sex, etc.).

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73