views:

150

answers:

3

The GNU C++ (g++ -pedantic -Wall) accepts this:

typedef int MyInt;

class Test
{
public:
    MyInt foo();
    void bar(MyInt baz);
}; 

int Test::foo()
{
    return 10;
}

void Test::bar(int baz)
{
}

int main(void)
{
    Test t;
    t.bar(t.foo());
    return 0;
}

Is it legal C++? Are other compilers likely to accept it?

+6  A: 

Regardless of whether it is legal it's not the best of practices. Typedefs exist so you can change the base type and have it reflected all over your code and if you ever do so you'll find suddenly your program doesn't compile anymore.

Kristoffon
+10  A: 

Yes it is legal:

7.1.3 The typedef specifier

A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.

AraK
This is right, but I think that "synonym for another type" and/or "does not introduce a new type" are the phrases that should be emphasized.
Michael Burr
@Michael. True :)
AraK
+1  A: 

Yes, it is legal.

It is questionable, since it's not obvious anymore how declaration and definition match, but if you have a good reason, you can do it.

Malte Clasen