1

how to give a prototype for class in c++ if i want to declare after main()? i wrote the following code fragment. i have refered to material available on cplusplus.com, i tried googling it but could not find anything useful.i by mistake the declared the class below main , but then i realised that i had not given a prototype for it and thus my program could not run.

#include<iostream.h>
#include<conio.h>

void main()
{
    student s;
    s.show();

    getch();
}

class student
{
    int age;
    public:
    void show();
};

void student::show()
{
    age = 5;
    cout << age;
}
CoderPi
  • 12,985
  • 4
  • 34
  • 62
srishti77714
  • 85
  • 1
  • 10

1 Answers1

2

You can't. student must be a complete type if you write student s;. A forward declaration is therefore not sufficient.

The obvious solution is to write the class declaration in a file called student.h and #include that at the top of the file that defines main().

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • i removed the function show from my program and then the program worked why so?? – srishti77714 Nov 25 '15 at 11:14
  • *That* is interesting. I think you should post that as a new question, perhaps under the title "why does this code compile and run despite my declaring an automatic instance of an incomplete type". And mention which compiler you're using. – Bathsheba Nov 25 '15 at 11:16