C++ Base class/Derived class usage causing a crash?

Viewed 53

I am trying to understand how inheritance works in C++. I understand that when using pointers, the base class must use a virtual destructor, and I get the reasoning behind it.

Assume I have a parent class.

struct Parent {
  Parent() = default;
  virtual ~Parent() = default;

  // And a constructor with specific args
  explicit Parent(std::string name, int age, std::string favoriteColor) : name(std::move(name)), age(age), favoriteColor(std::move(favoriteColor)) {}

  std::string name;
  int age;
  std::string favoriteColor;
  std::string address;
  std::string city;
  std::string state;
};

And a child class.

struct Child : public Parent {
  using Parent::Parent;
};

// What's the difference between ^^^ version and this:

struct Child : public Parent {
  public:
    explicit Child(std::string name, int age, std::string favoriteColor) : Parent(name, age, favoriteColor) {}
};

I'm able to create instances of Child, but I'm sometimes getting a crash with this code running on an old Ubuntu machine. Is there anything off with how I use the child?

std::string name = "johnny";
int age = 37;
std::string color = "red";

Child c{name, age, color}; // This is safe?
Parent &d = c; // Is this safe?

0 Answers
Related