Hellowhatsup
Hellowhatsup

Reputation: 21

Parent Class having an Array of Child Class

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();
}

Upvotes: 0

Views: 111

Answers (1)

The Dark
The Dark

Reputation: 8514

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.

Upvotes: 1

Related Questions