0

Basically, I have a base class called materials. Materials has many virtual functions, one of them is called a "Double DVD" (Which is a type of material, but is made up of two DVD's which are another material).

So at first I thought I'd store it as either a pair/vector of materials in a derived class called "Set" and have a virtual function defined in material.h that would return a vector of pointers to the two (or more) DVD objects stored.

virtual std::vector<DVD *> getPointers() { return std::vector<DVD *>(); }

However, the problem is that this necessitated the inclusion of "DVD.h" into Materials.h like this:

#ifndef CWK_MAT_H
#define CWK_MAT_H
#include "DVD.h"
#include <string>
#include <vector>
namespace MATERIALS
{ 

This caused the code to break in absolutely spectacular ways. Is there any way to get around this problem? I need the virtual method to get the pointers to be in the Materials class so that I can access it from this vector:

std::vector<Material *> vect;

As in

vect[1]->getPointers()

I tried to change it to a vector of materials but then it breaks (For some reason makes Visual Studio basically freeze, saying it's updating IntelliSense forever) when I change it to that in the derived class "set" (Set derives from Material, DoubleDVD derives from Set)

Is there any way to do this?

Mateusz J
  • 45
  • 7
  • Possible duplicate of [C++ - Forward declaration](http://stackoverflow.com/questions/4757565/c-forward-declaration) – xaxxon Apr 17 '16 at 00:15

1 Answers1

2

You can forward declare any class that you only use pointers or references to, instead of including the .h file with the full type information. simply type class DVD; before you use the vector of DVD pointers. A forward declaration is basically telling the compiler "hey, trust me, this type exists and I'll tell you more about it when you actually need that information". It works because pointers (and references, which are basically just fancy pointers) are always the same size, so the compiler doesn't actually NEED any more information to deal with them.

https://stackoverflow.com/a/4757718/493106

Also, by putting the code for functions in a .cpp file instead (where possible - templated class methods are sometimes not possible to do this with), you get rid of a lot of situations where you end up with circular includes, since nothing should be #include'ing .cpp files.

Community
  • 1
  • 1
xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • Oh wow, cool. Never figured out something like this existed. Thanks a lot, Xaxxon. – Mateusz J Apr 17 '16 at 00:15
  • happy to help. Just remember, before you refer to any members in the class, the full type information (the .h file) has to be present. so DVD* is fine, but myDvd->chapterList; or whatever requires the full type info. – xaxxon Apr 17 '16 at 00:16