help on some code

N

Nan Li

I ran into the following code. It seems you can have a class and a
variable/function share the same name. This is a little confusing,
though understandable. Also it's the first time I saw the notation
'class A' in creating the object.

Is this kind of usage mentioned in any book, web page or the standard?
I'd like to know more details about this code.

Thanks !

#include <iostream>

using std::cout;
using std::endl;

struct A
{
A() { cout << "A::A" << endl; }
};

int A = 1; //one of there two is ok
void A() {} //but not both

int main()
{
class A a;
cout << A << endl;
}
 
P

pelio

Nan Li a écrit :
I ran into the following code. It seems you can have a class and a
variable/function share the same name. This is a little confusing,
though understandable. Also it's the first time I saw the notation
'class A' in creating the object.

I think this is a remain of C style declaration when you had to declare
a struct variable like this:

struct MyStruct aStructInstance;

First implementation of C++ may have keep the same writing for class
variable declaration (or it has been allowed to keep consistent with old
C style declaration):

class MyClass aClassInstance;

Anyway, you should not use them anymore.
 
J

James Kanze

Nan Li a écrit :
I think this is a remain of C style declaration when you had
to declare a struct variable like this:
struct MyStruct aStructInstance;
First implementation of C++ may have keep the same writing for class
variable declaration (or it has been allowed to keep consistent with old
C style declaration):
class MyClass aClassInstance;

I don't think that this was ever required in C++, but you're
right that it's a hack for C compatibility. In C, "tags" (the
names of structs and enums) are in a totally separate namespace,
the name of a tag will only be found if it is immediately
preceded by struct, union or enum, and the name of anything else
will never be found in such cases. So C++ has a few special
rules (aka hacks) which allow you to use the same name (in the
same scope) for both a class and something else; if the name is
preceded by struct, class, union or enum, the name of the class
will be found, and otherwise, the name of whatever else will be
found. (This is very important when you start including headers
which were initially designed for C.)
Anyway, you should not use them anymore.

Not in C++ code, anyway. I might use it in special cases in a
header which was designed to be included in both C and C++ (but
even then, I think I'd generally prefer different names).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top