0

I am trying to write a C++ program with two classes.

class duck {
    Fly fls;
    /*...*/
};

class Fly
{
    /*...*/
};

In the above code I am trying to use object of class Fly in class duck but since the class Fly is declared after the class duck it shows the error:

Fly does not name a type

but if declare the class Fly before class duck the error does not come. How can I use an object of class Fly in duck when it is declared afterwards? thank you!

Sergey
  • 7,985
  • 4
  • 48
  • 80
SuperAadi
  • 627
  • 1
  • 6
  • 15

2 Answers2

0

It's simply not possible. When you use the type, it has to already exist.

The only exception is when you want to use just the pointer to that type, in that case it's enough to just declare its existence:

class Fly;

class Duck {
    Fly *fls;
    ...
};
...
class Fly {
    ...
};
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
0

How can I use an object of class Fly in duck when it is declared afterwards?

You can't. No way. Compiler does not know anything about the class before you declared it, so it cannot compile any code with it. But there are good news! You can use references and pointers to a class before it's definition. You just need to forward-declare it like this:

class Fly;

void foo(Fly &f_ref, const Fly& f_cref) {
    /* Using reference and const reference here */
}

class duck {
    Fly* fls_ptr; // Pointer.
    /*...*/
};

class Fly
{
    /*...*/
};

Here is a good overview on where you can use forward declarations.

Community
  • 1
  • 1
Sergey
  • 7,985
  • 4
  • 48
  • 80
  • @AADITHYAKRISHNAN Not exactly the same. In java you don't have explicit concept of pointers and references as different things. You can just write `Fly fls;` in your `duck` class and it will work. You don't need a forward declaration. I suppose, it's because in Java all objects of non-primitive types are passed around by reference. – Sergey Nov 03 '16 at 04:11