Question

It's the follow up question of this: error C2504 circular inclusion. Child if forward declared in parent's header.

It is not included, so the complier wont find Child? Then how do i instantiate a new Child object from Parent object.

Parent.h

#pragma once
#include <vector>

using std::vector;
class Child;
class Parent
{
public:
    Parent();
    void GiveBirth();
    ~Parent();
    vector<Child*> children;
};

Parent.cpp

#include "stdafx.h"
#include "Parent.h"


Parent::Parent()
{

}

void Parent::GiveBirth()
{
    Child ch = Child(); //Error: incomplete type is not allowed
}

Parent::~Parent()
{
}

Child.h

#pragma once
#include "Parent.h"
class Child : Parent
{
public:
    Child();
    ~Child();
};

Child.cpp

#include "stdafx.h"
#include "Child.h"


Child::Child()
{
}


Child::~Child()
{
}
Was it helpful?

Solution

Here are some reading list for you.

http://en.wikipedia.org/wiki/Opaque_pointer

http://en.wikibooks.org/wiki/C%2B%2B_Programming/Idioms#Pointer_To_Implementation_.28pImpl.29

Parent.cpp

#include "stdafx.h"
#include "Parent.h"
#include "Child.h"


Parent::Parent()
{

}

void Parent::GiveBirth()
{
    //Child ch = Child(); //Error: incomplete type is not allowed
    children.push_back(new Child());
}

Parent::~Parent()
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top