Keeping int main() at the top when using classes and objects.

0 Christopher Cullen · April 1, 2015
Hello everyone!

I've just watched the 12th C++ tutorial video regarding classes and objects. I'm fine with what is being done but would like to know how to keep the int main() part of the code at the top. As it's the first thing the program looks for when running it makes more sense in my head to have it there, unless I'm prototyping a function.

Here's my code currently (adapted slightly from the video):

#include <iostream>

class ChrisClass{
    public:
        void BritishSaying(){
            std::cout << "Tea anyone?" << std::endl;
        }

};

int main()
{
    ChrisClass ChrisObject;
    ChrisObject.BritishSaying();
    return 0;
}



I'd prefer it to read like this:

#include <iostream>

- I know something needs to go here

int main()
{
    ChrisClass ChrisObject;
    ChrisObject.BritishSaying();
    return 0;
}

class ChrisClass{
    public:
        void BritishSaying(){
            std::cout << "Tea anyone?" << std::endl;
        }

};


Many thanks!

Post a Reply

Replies

Oldest  Newest  Rating
+1 zahidul haque · April 2, 2015
If you write your main() method first then the compiler will give you the compilation error.
The compiler will look for the class ChrisObject and will say what a hack :) where if this class or it's object is declared.

The best way you can define in separate header fill and main in separate file. Include the header file in the file where you have defined your main().

In .h file, if tomorrow you need other class's object or method you can also do the forward declaration, so that the compiler will not complain.

you can understand forward declaration as extern which we use in C lang, telling that my function or variable is defined somewhere else.

Hope this will help you.
0 Christopher Cullen · April 2, 2015
Thank you both for the answers. 

Would you say it is better to not prototype functions very often, if at all?
0 zahidul haque · April 2, 2015
prototyping is c style. If your class is written as a c style then it's a different story.
Also you will lose the features of OOP
0 Christopher Cullen · April 5, 2015
Many thanks again guys, you've been very helpful. 
  • 1

C++

106,942 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator