class named main

Mar 9, 2016 at 5:42am
Can I have a class named main in C++? Is this possible?? then how can i create objects..

#include<iostream.h>
class main
{
public:
int x;
}; // upto this it will works
void main()
{
main n; // here it says error
n.x=10; // error
}
Mar 9, 2016 at 5:57am
Can I have a class named main in C++?

Since main is not a reserved word, yes. But your problem is that you're trying to have a function and a variable with the same name in the same scope, that will cause problems.

Last edited on Mar 9, 2016 at 6:00am
Mar 9, 2016 at 7:15am
how to set different scope..
Mar 9, 2016 at 8:00am
Why don't you name the class something more descriptive instead? The word "main" doesn't tell you what the class is about.
Last edited on Mar 9, 2016 at 8:01am
Mar 9, 2016 at 8:47am
but the question i am having is
Can you have a class named main in C++? If yes, how do you call its constructor?
Mar 9, 2016 at 9:05am
You could place the main class inside a namespace.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace A
{
	class main
	{
	public:
		int x;
	};
}

int main()
{
	A::main n;
	n.x = 10;
}
Topic archived. No new replies allowed.