0

I try to get familiar with C++ inheritance. I tried to overload a base class constructor in a inherited class. I can see that I call the correct base constructor from my inherited class, but afterwards the initialized values are empty/not reflected in the inherited class.

I read plenty of answers regarding this question on stackoverflow but I am not sure why the variables from the base class are not accessible to the inherited class.

#include <iostream>
#include <string>

using namespace std;
class person {
public:
  string name, surname;
  int age;

  person() {
    name = "";
    surname = "";
    age = 0;
  }
  person(string iName, string iSurname, int iAge) {
    setName(iName);
    setSurname(iSurname);
    setAge(iAge);
  }

  void setName(string iName) { name = iName; }
  void setSurname(string iSurname) { surname = iSurname; }
  void setAge(int iAge) { age = iAge; };
  string returnPerson() {
    return name + " " + surname + " " + to_string(age) + "\n";
  }
};

class personExtended : public person {
public:
  string job;

  using person::person;
  personExtended() {
    person();
    job = "";
  }
  personExtended(string iName, string iSurname, int iAge, string iJob) {
    person(iName, iSurname, iAge);
    setJob(iJob);
  }
  void setJob(string iJob) { job = iJob; };
};

int main() {
  personExtended myPerson("Jon", "Arryn", 49, "Knight");
  cout << myPerson.returnPerson();
}

Output will be empty

I'd be glad if someone could explain me why the value from the base class will be lost upon the return of the call of the constructor of the base class. I my approach completely wrong?

Why are the variables name/surname not filled if I call the constructor from a inherited class? If I call the base class constructor it works fine and as far as I understand, the public variables from the bass class, which are set by the base class constructor, should also be available for the inherited class.

Thanks for helping me to understand c++ a little bit better =)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Luke
  • 3
  • 2
  • You need to call the base class constructor in the constructor initializer list. `personExtended(string iName, string iSurname, int iAge, string iJob) : person(iName, iSurname, iAge), job(iJob) {}` – Retired Ninja Dec 10 '21 at 21:33
  • Thanks you sir, that solved my problem. – Luke Dec 10 '21 at 21:35

0 Answers0