Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i separate a class definition into 2 header files?

Tags:

c++

class

I need to split one class (.h file)

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  L();
  firstoperator(..);
  secondoperator(..);
private:
 ...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...
template <class L> Myclass<L>::secondoperator(..) ...

in two different .h file in the following form:

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  L();
  firstoperator(..);
private:
 ...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  secondoperator(..);
}

template <class L> Myclass<L>::secondoperator(..) ...

how can I do it correctly without conflict?

Thank you in advance.

like image 729
Ordi Avatar asked Sep 23 '14 17:09

Ordi


3 Answers

You can technically do it, but it's ugly. Don't do it.

Class1.hpp:

class MyClass
{
    int something;
    int somethingElse;

Class2.hpp:

    int somethingBig;
    int somethingSmall;
};

I hope it's clear how disgusting that is :)

like image 161
tenfour Avatar answered Oct 16 '22 06:10

tenfour


You can use heritage to split class to two headers.

You can declare half class on the base and the other half on the derived.

like this:

class C12{
public:
  void f1();
  void f2();
};

can be splitted to C1 and C12

class C1{
public:
  void f1();
};

class C12: public C1{
public:
  void f2();
};

now C12 is the same as before but splitted to 2 files.

like image 26
SHR Avatar answered Oct 16 '22 07:10

SHR


"how can I do it correctly without conflict?"

You can't. It's not possible in c++ to spread a class declaration over several header files (unlike as with c#). The declarations of all class members must appear within the class declaration body, at a single point seen in each translation unit that uses the class.

You can separate template specializations or implementation to separate header's though.

like image 45
πάντα ῥεῖ Avatar answered Oct 16 '22 06:10

πάντα ῥεῖ