Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declaring with inheritance information

This compiles fine, although I wouldn't want to try running it just yet. However ...

//class base;
//class derived;
//class derived : public base;

class base {};
class derived : public base {};

class other
{
    public:
        void func() {base1 = derived1;}
        base* base1;
        derived* derived1;
};

void main()
{
}

... moving the class other to above the definition of base and derived for which there is a similar thing I must do in a program of myne causes compile errors.

The obvious solution is to forward declare base and derived shown commented out at the top of the code, however this causes a can't convert between base* and derived* error. Attempting to forward declare including the inheritance information dosn't work either.

like image 259
alan2here Avatar asked Jan 16 '11 20:01

alan2here


People also ask

Should I use forward declaration or include?

As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .

What does forward declaration do?

A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.

Why are forward declarations necessary?

Forward declarations means the declaration of a method or variable prior to its implementation. Such declaration is necessary in C/C++ programming language in order to be able to use a variable or object before its implementation.

Where do you put forward declaration?

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.


1 Answers

This should work. You need to move other up

BUT declare func below. That way func is able to "see" that derived is of type base.

e.g.,

class base;
class derived;
//class derived : public base;

class other
{
    public:
        void func();
        base* base1;
        derived* derived1;
};

class base {};
class derived : public base {};

void other::func() { base1 = derived1; }
like image 195
AbstractDissonance Avatar answered Oct 26 '22 09:10

AbstractDissonance