class prototype and objects.

Confused!
I'm doing the tutorial TheNewBoston made. I'm currently at "Introduction to Classes and Objects".

My problem is i really like prototypes to keep it "clean" (at least in my head) so when i try follow his instructions but with a prototype implemented, it wont work??

Heres the code of the one that wont work.
It has the error "aggregate 'AClass aObject' has incomplete type and cannot be defined":

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class AClass;

int main()
{
   AClass aObject;

   aObject.coolSaying();

    return 0;
}

class AClass
{
    public:
        void coolSaying()
        {
            cout << "preachin to the choir \n";
        }
};


The code that works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class AClass
{
    public:
        void coolSaying()
        {
            cout << "preachin to the choir \n";
        }
};

int main()
{
   AClass aObject;

   aObject.coolSaying();

    return 0;
}


So to sum up my question:
How do i keep the prototype or make some other thing so that i can keep the main at the top?
Last edited on
If you're willing to split your code up into multiple files, you could do it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// AClass.h
#ifndef ACLASS_H
#define ACLASS_H

#include <iostream>

class AClass
{
    public:
        void blah()
        {
            std::cout << "Blah!";
        }
};

#endif 
1
2
3
4
5
6
7
8
// main.cpp
#include "AClass.h"

int main()
{
    AClass a;
    a.blah();
}

Otherwise, you'll have to put the class definition at the top, before main.

If you typically define your member functions inside of the class definition, you can shave off a little room from the top by moving those definitions below main:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

class AClass
{
    public:
        void blah();
};

int main()
{
    AClass a;
    a.blah();
}

void AClass::blah() // If using multiple files, this would typically go in a separate .cpp file
{
    std::cout << "Blah!";
}
Thanks for the fast awnser :)
But that is kinda sad to hear but i guess that is the best i can get :|
Topic archived. No new replies allowed.