0

I have two classes: Meter and Feet. Each has a method that converts its value into the other and returns the other object. For example, Meter has a method toFeet() that returns a Feet object, and vice-versa.

I have used forward declaration. I have also tried including and (as suggested in another post) not including other class' header files.

Meter.h

...
class Feet; // forward declaration
class Meter {
public:
    ...
    Feet toFeet() const { return Feet(...); }
    ...
};

Feet.h

...
class Meter; // forward declaration
class Feet {
public:
    ...
    Meter toMeter() const { return Meter(...); }
    ...
};

I get the following error:

In member function 'Feet Meter::toFeet() const':
error: return type of 'class Feet' is imcomplete
{
^

error: invalid use of incomplete type 'class Feet'

error: forward declaration of 'class Feet'

So what conceptual stuff did i miss here?

EDIT: The post was marked as duplicate to one in which the answer is forward declaration. But I had tried that before posting this problem.

Anyway, my accepted (and very simple) solution was to separate declarations and definitions of methods.

munikarmanish
  • 352
  • 2
  • 3
  • 13
  • 8
    Only declare the two methods in the header file. Move the actual implementation to source files. Each source would include both Meter.h and Feet.h – Igor Tandetnik Dec 26 '14 at 02:51
  • 1
    Why not use `friend` classes? – Jake0x32 Dec 26 '14 at 02:51
  • 2
    The forward declaration will only work for a pointer. If the class definition is not available then the compiler is unable to create the actual object from the class definition since at that point the class definition does not exist, only a declaration that a definition is forthcoming. So a quick fix is to create pointers to an object of class feet or class meter so that the compiler will compile. However then you have the problem of memory ownership and deleting the created objects once their life time has expired. – Richard Chambers Dec 26 '14 at 02:56
  • Why not just use functions? – Nasser Al-Shawwa Dec 26 '14 at 03:01
  • @IgorTandetnik: Well, separating definitions from declaration did the trick. Thanks! – munikarmanish Dec 26 '14 at 03:03
  • @Nasser: We're just starting to learn C++ this semester and this was kind of an assignment to practice classes & objects. :) And the classes are not just for conversions; they have other behaviours as well. – munikarmanish Dec 26 '14 at 03:05
  • @Pradhan: the answer to that post was **forward declaration**, which didn't solve my problem. That's why I posted. – munikarmanish Dec 26 '14 at 10:50

0 Answers0