26

Can we alias a class name the way we do in namespaces?

For example:

namespace longname{ }
namespace ln = longname;// namespace aliasing

class LONGNAME {};
class LN = LONGNAME; // how to do class name aliasing, if allowed?
ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
Jatin
  • 1,857
  • 4
  • 24
  • 37

4 Answers4

34

Simple:

typedef LONGNAME LN;

Typedefs are used in C++ a bit like "variables which can store types". Example:

class Car
{
public:
    typedef std::vector<Wheel> WheelCollection;

    WheelCollection wheels;
};

By using Car::WheelCollection everywhere instead of std::vector<Wheel>, you can change the container type in one place and have all your code reflect the changes. This is the C++ way to abstract data types (whereas eg. in C# you'd have a property returning IEnumerable<Wheel>).

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
20

Beside the answers already provided using the keyword typedef, you also can use the keyword using since C++11. IMHO it looks more consistent regarding the aliasing.

namespace longname{ }
namespace ln = longname;// namespace aliasing

class LONGNAME {};
using LN = LONGNAME; // "class aliasing"

In addition, with using you are able to alias template classes (How to typedef a template class?) by using alias templates.

template<typename T> class LONGNAME {};
template<typename T> using LN = LONGNAME<T>; // alias template
Community
  • 1
  • 1
user1810087
  • 5,146
  • 1
  • 41
  • 76
6

You can use the typedef keyword:

typedef LONGNAME LN;

You can also do something like:

typedef class {

...

} LN;

Edit: You may run into trouble when using templates though. See here for a possible solution.

Community
  • 1
  • 1
ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
1
typedef int mark;  // for in built data types

class abc
{
};

typedef abc XYZ; // for user written classes.

Typedef allows you to alias a class or datatype name with a more context sensitive name corresponding to the scenario.

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112