6

I am not able to find a similar question else where on this site, but is it possible to declare a class over two different files.

for example, all public class components in a file and privates and others in a different file.

publics.h

    class test {
     public:
        int geta();
        void seta(int); 
    };

privates.h

    class test {
     private:
        int a;
    };

The above way is definitely wrong, but is there any such method.

nagavamsikrishna
  • 809
  • 1
  • 10
  • 21

3 Answers3

8

There is a way to get something quite similar: private inheritance.

// private.hpp
class test_details {
  protected:
    int a;
};

// public.hpp

#include "private.hpp"

class test : private test_details {
  public:
    int geta() const { return a; }
    void seta(int i) { a = i; }
};

Note that you will still need to (indirectly) include the private header in any module that uses the public class, so you're not really hiding anything this way.

Fred Foo
  • 328,932
  • 68
  • 689
  • 800
  • haha. I like the solution very much. clever. clean. But I'll wait before marking yours as the best answer. – nagavamsikrishna Jul 03 '12 at 09:53
  • Well, just that the private data-members and functions are not portable. So we wanted them to be in a different location altogether. Your solution solves the problem. (I can't stop smiling at the solution!!) – nagavamsikrishna Jul 03 '12 at 10:57
6

Not like that, but the pimpl idiom (or opaque pointer, or Chesshire cat) can help you achieve similar functionality - you can provide a public interface where all implementation details are hidden in an implementation member.

C++ doesn't support partial classes.

Also, note that what you have there are class definitions, not declarations. C++ mandates that if multiple definitions of a class are available, they must be identical, otherwise it's undefined behavior.

Luchian Grigore
  • 236,802
  • 53
  • 428
  • 594
1

This is a good use case for an abstract base class

 //File test.h
 class test {
     public:
        virtual ~test() {}
        virtual int geta()=0;
        virtual void seta(int)=0; 
    };

 //File test_impl.h
 class test_impl : public test {
     public:
        int geta() { return a; }
        void seta(int a ) { a = v; }
     private:
        int a;
    };
Michael Anderson
  • 61,385
  • 7
  • 119
  • 164