exestive exestive - 18 days ago 5
C++ Question

":" Colon in a Struct constructor

I have checked some topics about Bitfields in a struct constructor, but I couldn't find any explanation about this line of code:

vertex(string s) : name(s) {}


in this block of code:

struct vertex {
typedef pair<int, vertex*> ve;
vector<ve> adj; //cost of edge, destination vertex
string name;
vertex(string s) : name(s) {}
};


The whole code structure is about implementing a weighted graph which I have seen in this Website:

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct vertex {
typedef pair<int, vertex*> ve;
vector<ve> adj; //cost of edge, destination vertex
string name;
vertex(string s) : name(s) {}
};

class graph
{
public:
typedef map<string, vertex *> vmap;
vmap work;
void addvertex(const string&);
void addedge(const string& from, const string& to, double cost);
};

void graph::addvertex(const string &name)
{
vmap::iterator itr = work.find(name);
if (itr == work.end())
{
vertex *v;
v = new vertex(name);
work[name] = v;
return;
}
cout << "\nVertex already exists!";
}

void graph::addedge(const string& from, const string& to, double cost)
{
vertex *f = (work.find(from)->second);
vertex *t = (work.find(to)->second);
pair<int, vertex *> edge = make_pair(cost, t);
f->adj.push_back(edge);
}


What does this bit do and what is the purpose?

vertex(string s) : name(s) {}

Answer

vertex is the struct name, so vertex(string s) is a constructor with a string parameter. In a constructor, : begins the member initialization list, which initializes member values and calls member constructors. The following brackets are the actual constructor body, which in this case is empty.

See Constructors and member initializer lists for more details.

Comments