I'm writing a class that represents a graph, so I've wrote the following header
class Graph {
public:
Graph();
Graph(int N);
void addVertex();
void addEdge(VertexNum v1, VertexNum v2, Weight w);
std::pair<PathLength, Path> shortestPath
(const VerticesGroup& V1, const VerticesGroup& V2);
private:
typedef int VertexNum;
typedef int Weight;
typedef std::pair<VertexNum, Weight> Edge;
typedef std::vector<Edge> Path;
typedef size_t PathLength;
typedef std::vector<VertexNum> VerticesGroup;
std::vector<std::list<Edge> > adjList;
bool incorrectVertexNumber(VertexNum v);
};
I have some questions about the above code:
First way is to typedef at the place-of-first-declaration. Second way is to typedef at each place-of-use, and make it only visible to that place-of-use (by putting it inside the class or method that uses it).
If you restrict using the typedef ed name within your class, then make it private . It is certainly common practice to rename a type using typedef to a more usable/easily understandable name at the domain level.
typedef keyword is used to assign a new name to any existing data-type. For example, if we want to declare some variables of type unsigned int, we have to write unsigned int in a program and it can be quite hectic for some of us.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
1. Access control in C++ is applied purely to names. There's a note and example in ISO/IEC 14882:2011 11 [class.access]/4 that makes it clear that this is the intention.
[...] [ Note: Because access control applies to names, if access control is applied to a typedef name, only the accessibility of the typedef name itself is considered. The accessibility of the entity referred to by the typedef is not considered. For example,
class A {
class B { };
public:
typedef B BB;
};
void f() {
A::BB x; // OK, typedef name A::BB is public
A::B y; // access error, A::B is private
}
—end note ]
2. it is ok, as you can make some type meaningful and easily understandable.
Any typedef
used in the public
interface of the class should be in the public
section of the class. Rest should be private
.
private
, you will not be able to use them outside your class. I guess this is not what you want, specially if the typedef
ed name appears as parameter type in your public interface. If you restrict using the typedef
ed name within your class, then make it private
.typedef
to a more usable/easily understandable name at the domain level.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With