Max Martinez
Max Martinez

Reputation: 1

Error trying to make a class run with main

This is the code:

#include <iostream>
using namespace std;
class A;

int main(){
    A aObject;
    aObject.cool();
    return 0;
}
class A{
    public:
        void cool(){
            cout << "hi";
        }
 };

But when I try to run it i get this error:

||=== Build: Debug in First (compiler: GNU GCC Compiler) ===| In function 'int main()':|

error: aggregate 'A aObject' has incomplete type and cannot be defined|

||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Help!

Upvotes: 0

Views: 201

Answers (3)

Christian Hackl
Christian Hackl

Reputation: 27528

#include <iostream>
using namespace std;
class A;

int main(){
    A aObject;

At this point, the compiler only knows that there is a class called A. It does not yet know anything else about it. It does not know its size and it does not know how to construct an object of the class. It needs its definition to construct an object.

The following program works because the compiler knows the definition of the class at the point where you create an object of it:

#include <iostream>
using namespace std;

class A{
    public:
        void cool(){
            cout << "hi";
        }
 };

int main(){
    A aObject;
    aObject.cool();
    return 0;
}

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 59997

You got stuff arse over tit. Try this:

#include <iostream>
using namespace std;

class A{
    public:
        void cool(){
            cout << "hi";
        }
 };
int main(){
    A aObject;
    aObject.cool();
    return 0;
}

Upvotes: 2

Ren P
Ren P

Reputation: 927

Move class A to before the main function.

Upvotes: 1

Related Questions