c++ - Keeping a pointer to another class -


i want keep pointer (or reference) class. class contains matrix of pointers base class, , want able use public functions of class inside function of class has pointer (or reference) it. let's looks this:

base.h

#pragma once  class base { protected:     int x;     int y; public:     void setx (int _x)     {         x=_x;     }     void sety (int _y)     {         y=_y;     }     virtual void f ()=0; }; 

derived.h

#pragma once #include "base.h" #include "container.h"  class derived : public base { private:     container* c; public:     derived (container* c, int x, int y)         : c(c)     {         setx(x);         sety(y);     }      void g ()     {         c->dostuff();     }      virtual void f ()     {         std::cout<<"f"<<std::endl;     } }; 

container.h

 #pragma once  #include "base.h"  #include "derived.h"   class container  {  private:     base*** mat;  public:     container ()     {         mat=new base**[10];         (int i=0; i<10; ++i)             mat[i]=new base*[10];          (int i=0; i<10; ++i)             (int j=0; j<10; ++i)                 mat[i][j]=null;          mat[5][5]=new derived(this, 1, 2);      }      void dostuff ()     {         std::cout<<"stuff"<<std::endl;     }  }; 

i keep getting these errors

derived.h(8): error     c2143: syntax error : missing ';' before '*' derived.h(8): error c4430: missing type specifier - int assumed. note: c++ not support default-int derived.h(10): error c2061: syntax error : identifier 'container' derived.h(10): error c2065: 'c' : undeclared identifier derived.h(12): error c2614: 'derived' : illegal member initialization: 'c' not base or member derived.h(19): error c2065: 'c' : undeclared identifier derived.h(19): error c2227: left of '->dostuff' must point class/struct/union/generic type 1>          type ''unknown-type'' container.h(20): error c2661: 'derived::derived' : no overloaded function takes 3 arguments 

i know i'm missing , can't pinpoint is

you have cyclic include dependency between container.h , derived.h. fortunately, can avoided, since derived not need full definition of container, can use forward declaration instead of include:

#ifndef derived_h_ #define derived_h_ #include "base.h"  class container; // fwd declaration  class derived : public base { private:     container* c;  //... before  #endif 

you need #include "container.h" in implementation of derived.

as general rule, should include needs included, , nothing more.


Comments