class declaration

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

using namespace std;

class Foo;


int main(){
    Foo bar;
    
    return 0;
}

class Foo{
    public:
        Foo(){
            cout << "constructor created" << endl;
        }

};



Why do I get an error? how do I declare my class?
Just put the class above main, or in an h-file.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo{
public:
	Foo(){
		cout << "constructor created" << endl;
	}

};

int main(){
	Foo bar;

	return 0;
}


Edit: Im not sure how you would prototype your Class.
Last edited on
So you can't prototype classes. But still functions can do, right?
Yes! Functions will work fine.

1
2
3
4
5
6
7
8
9
10
11
int test(int x);

int main()
{

}

int test(int x)
{

}


I know that you can prototype classes, Ive done it plenty of times. But, Ive only done it in other H files. For example, if I had 2 classes, I would prototype class 1 above class 2. Ive never done it in the main.cpp nor do I know if it can be done (getting an error aswell).

Last edited on
This is abuse of the term "prototype".

A class is a "type".

Your forward declaration in line 5 just tells us the type exists, not how to create it.

At line 10, you're trying to create an object. At this point, the type of the object is not known so it cannot be created.

For example, we don't know the size (do we have to make some space for it on the stack)? Base classes to be initialised? Member objects? Memory allocated on heap? In short, we need to call the constructor, as implied by the name, to construct the object.

To put it in (very) crude terms, as you pointed out, you can prototype a function and call it before the definition is seen, but you can't use it before the prototype (declaration) is seen. The same thing is true here - we need to have seen the "constructor prototype", before we can create the object.

Look at it this way:

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

using namespace std;

class Foo
{
public:
    Foo();
};

int main()
{
    Foo bar;
    return 0;
}

Foo::Foo()
{
     cout << "constructor created" << endl;
}
Topic archived. No new replies allowed.