PAPAmidNIGHT
PAPAmidNIGHT

Reputation: 59

class composition and header problems

Currently, I'm writing a project for fun and faced next problem.Let's suppose I'm creating class Bank and I want to define classes LoginController and Departure

class Bank{
    class LoginController{
       //some implemantation 
    }
    class Departure{
       //some departure 
    }
}

To avoid making huge declaration of Bank inside Bank.h I want to define them in separate files

//Bank.h
#include "LoginController.h"
#include "Departure"
class Bank{
  class LoginController;
  class Departure;
  LoginController controller;  
  Departure departure;
  ...
}
//LoginController.h
class Bank; //forward declaration
class Bank::LoginController{
   bool getAccess(Bank::Departure);
}
//Departure.h
//Departure depends on Bank class aswell
class Bank; //forward declartion
class Bank::Departure{...}

This code wont compile with huge stack trace.It can be solved with one big Bank.cpp and writing it all there, however, i don't want to make one huge file. I assume this is a bad design problem, however, i'm still interested if it possible to implement this class as I wanted.Even if I define LoginController && Departure structure inside Bank i want separate cpp files for each class, however, header guard will close access to it after including it to one of cpp files.The best solution i can see is defining all in one header but not inside each other.

And one more question.Is it possible to define 1 header file with all includes like

#ifndef HeaderFile
#define HeaderFile
  #include <iostream>
  #include <memory>
  ....
#endif

From the previous question, i understand that this will open only for one file, therefore do we need to provide each file with needed headers. Including the same header to different files seems expensive.

Upvotes: 0

Views: 167

Answers (1)

Barmar
Barmar

Reputation: 782107

You can put the #include directives inside the Bank class.

Bank.h

class Bank {
    #include "LoginController.h"
    #include "Departure.h"
    // Bank implementation
}

LoginController.h

class LoginController {
    // some implementation
}

Departure.h

class Departure {
    // some implementation
}

Upvotes: 2

Related Questions