0

I'm just wondering if it'd be possible to have a class which is inside another class but in a different file. For example, if I have this:

//Master.h
class Master {
public:
    class subclass;

    subclass sc;
    Master() {
        sc.sayHi();
    }
};

//subclass.cpp
class Master::subclass {
public:
    void sayHi(){
        std::cout << "hi" << std::endl;
    }
};

Then the subclass's definition doesn't work, the Master class treats it like a blank class. I want to only state in one line that "subclass" should be a part of "Master", but not have to write any of subclass's code in Master.h, how can I fix that?

BubLblckZ
  • 115
  • 5
  • 2
    No. `subclass sc;` requires a class defined. You can use a pointer or a smart pointer there. – S.M. Jan 18 '20 at 16:50
  • [Why should the “PIMPL” idiom be used?](https://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used) – Evg Jan 18 '20 at 16:51

1 Answers1

1

You can include the separate subclass header file at the position where you would define the subclass. I do not think that this would improve code quality/readability.

It would like like this:

//Master.h
#include <iostream>
class Master {
public:
#include "subclass.h"
    subclass sc;
    Master() {
        sc.sayHi();
    }
};

// subclass.h
class subclass {
public:
  void sayHi(){
      std::cout << "hi" << std::endl;
  }
};
Gerriet
  • 1,097
  • 12
  • 19