why facing problem with this ??

In this code what is wrong ??
#include <iostream>
using namespace std;
class a
{
public :
a(int i)
{
cout<<i<<endl;
}
} a(2); /*please someone clear me about this line*/
int main()
{
a b(1); /*If I write, class a b(1); instead of the given line the program become ok. why ?? */
return 0;
}

This code:
1
2
3
4
class Foo
{
  //...
} bar;


Is exactly the same as this code:

1
2
3
4
5
6
class Foo
{
  //...
};

Foo bar;


What you have here, is you have a class named a, but then you are also creating an object named a. It'd be like doing this:

 
a a(2);


This is perfectly legal. However you now have a problem where this 'a' name is the name of an object which takes precedent of the name of the class.

So later, when you do this:

 
a b(1);


The compiler sees that a and it thinks you mean the object a and not the classname a. So it'll give you a compiler error because that makes no sense.

However if you prefix that line with the class keyword... you are clarifying that you mean the class name and not the object name.

 
class a b(1); // now it understands you want the 'a' class, not the 'a' object. 





Of course, a better solution would be to name your object something else so it doesn't conflict with the class name:

1
2
3
4
5
6
7
8
class a
{
  //...
} c(2); // <- don't name this 'a'

int main()
{
  a b(1); // then this is fine 
Compiler thinks that a (in the second case) is a variable, not a type.

You can either write
1
2
3
4
5
6
7
8
9
10
11
12
13
class a
{
public :
a(int i)
{
cout<<i<<endl;
}
} c(2); // c is an object of type a
int main()
{
a b(1); // a is a type
return 0;
}


or
1
2
3
4
5
6
7
8
9
10
11
12
13
class a
{
public :
a(int i)
{
cout<<i<<endl;
}
};
int main()
{
a b(1); // a is a type
return 0;
}
Thanks a lot .
Now it's clear to me. :) :)
Topic archived. No new replies allowed.