BubLblckZ
BubLblckZ

Reputation: 463

Is it possible to put a class declaration and definition in different files?

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?

Upvotes: 0

Views: 61

Answers (1)

Gerriet
Gerriet

Reputation: 1350

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;
  }
};

Upvotes: 1

Related Questions