Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration between files

All:

I have two files:

main.cpp

#include <iostream>

using namespace std;

class A;

int main(){
    A a;
    a.disp();

    return 0;
}

and A.cpp

#include <iostream>
using namespace std;

class A{

    public:
    A(){}
    void disp(){ cout<<"this is A disp()"<<endl;}
};

I wonder why when I compile this two files, it told me that:

main.cpp: In function ‘int main()’: main.cpp:8:4: error: aggregate ‘A a’ has incomplete type and cannot be defined

I think it because I do not understand how to use forward declaration, so can someone tell me how to do this?

BTW, I know the header file way to do this, but I just want to figure out in this forward declare way.

best,

like image 604
Kuan Avatar asked Dec 26 '22 05:12

Kuan


2 Answers

Since you are only declaring it as a class (i.e. you don't tell the compiler what the class contains), it is unable to create memory for it (it doesn't know how big it needs to be).

What you can do is define pointers to an A class:

int main(){
    A *a;
    // a->disp() is still invalid

    return 0;
}

but you won't be able to do anything with it.

This is exactly what headers are for!

A.h:

class A{
public:
    A(){}
    void disp();
};

A.cpp:

#include "A.h"
void A::disp(){
    cout<<"this is A disp()"<<endl;
}

After including a.h in a file, you will be able to create & use it as you would expect.

like image 185
Dave Avatar answered Jan 08 '23 02:01

Dave


main needs to know the size of class A, and that it has a member function disp(). For this reason, must have access to the class declaration. Put it in a file A.h (with include guards and no using namespace std), and include that in main.cpp.

file A.h

#ifndef A_H_
#define A_H_

#include <iostream>

class A
{
    public:
    A(){}
    void disp() const { 
      std::cout<<"this is A disp()"<<std::endl;
    }
};

#endif

main.cpp:

#include "A.h"

int main() { .... }

Note that you could decide to put the implementation of void A::disp() in an A.cpp file instead of in the header.

like image 37
juanchopanza Avatar answered Jan 08 '23 02:01

juanchopanza