0

With c++, I am trying to create a class called "family". Family is parent class of child class "man," and I'm trying to create an array of "man" in family class, but in order to do that, I need to include man.hpp in family.hpp. But this messes things up really bad... as now man doesn't acknowledge family as a base class.

So my question is this: How can I Include an array of child class in a parent class?

Thanks in advance!

#ifndef Family_hpp
#define Family_hpp
//here I want to include "include "man.hpp"" but this messes up."

class Family {
public:
//functions and constructor

private:
Man** manarray;

};

and here's family_cpp

#include "Family.hpp"
#include "Man.hpp"
#include<iostream>
#include<string>

using namespace std;

Family::Family()  {

}

void Family::setMen(int n) {
for (int i = 0; i < n; i++) {
    *(manarray+ i + 1) = new man();
}
Hellowhatsup
  • 151
  • 3
  • 4
    Please provide your attempt at coding this. – P.W Dec 13 '18 at 05:18
  • 2
    *Family is parent class of child class "man,"* This is a totally wrong use of inheritance. – n. m. could be an AI Dec 13 '18 at 05:21
  • A handy tool for telling whether or not inheritance makes sense: [Liskov Substitution Principle](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle) – user4581301 Dec 13 '18 at 05:23
  • Besides the inheritance misconception, using raw pointers in C++ is considered very bad practice. I encourage you to learn how to use resources such as `std::vector` and `std::shared_ptr` as soon as possible. – To마SE Dec 13 '18 at 08:03

1 Answers1

1

You can add a forward declaration if the Man class in your family.hpp file.

//here I want to include "include "man.hpp"" but this messes up."
class Man;

class Family {
...

This tells the compiler that Man is a class, without having to declare it fully. This will work in your case, as (currently) the compiler doesn't need to know anything else about Man to compile the header file.

The Dark
  • 8,453
  • 1
  • 16
  • 19