How to write a class library in c++ like the one we write for functions

For a library of functions,
we write

1. Function Declarations in MyFuncLib.h
2. Function Definitions in MyFuncLib.cpp
3. Then include the MyFuncLib.h in our Source.cpp to use any of the library functions.


Could we use the same prototype for a library of Classes to use the Class objects in our Source.cpp
i.e. can we

1. Declare classes in MyClassLib.h
2. Define classes in MyClassLib.cpp
3. Then include MyClassLib.h in Source.cpp and directly make the objects of the classes declared in MyClassLib.h

I tried this and got Error aggregate '<ClassType> x' has incomplete type and cannot be defined where ClassType is one of the classes declared in MyClassLib.h
Post your code here so we can see what would be causing the problem.
There is a difference between the declaration of a class name --- e.g., class Foo;, and the definition of a class, e.g., class Foo {};.

In the first case, class Foo; says that there is a type named Foo, but nothing more -- the compiler has no idea what a Foo is; it has incomplete type only until its definition is visible.

In the second case, class Foo {...}; says that there is a type name Foo along with what makes up any particular Foo.

Once that is visible, Foo has complete type.

Note that a definition of a class does not that imply the definition of its member functions. Those probably shouldn't be in the header file, because they'll slow down compilation and will arguably make the header file harder to read.

Those member function definitions can go in another translation unit (TU, think "a source file and everything included by it"); the compiler just has to know each member function exists before it sees it.

Example:
Foo.hxx
1
2
3
4
5
6
7
8
9
# if ! defined PROJECT_HEADER_FOO_HXX
# define PROJECT_HEADER_FOO_HXX

class Foo {
public:
  int bar(int baz);
}

# endif  


Foo.cxx
1
2
3
4
# include "foo.hxx"
int Foo::bar(int baz) { 
  return baz + 1; 
}
Last edited on
Thanks mbozzi :), this was really useful. I am now clear of why I was getting the error.
Thanks Jayhawk :) for your response too, mbozzi's explanation has clarified my doubts.
Topic archived. No new replies allowed.