0

The struct is defined like this:

 struct Edge {
    int weight;
    Vertex* v1;
    Vertex* v2;
  };

I need to do something like

new Edges(v1, v2, v3);

but that could only be done with a "class" and using ctor. How can I create a new element of struct and initialize it at the same time?

Thanks!

Alok Save
  • 202,538
  • 53
  • 430
  • 533
JASON
  • 7,371
  • 9
  • 27
  • 40
  • 2
    Why use `new` at all? Anyway, you're looking for aggregate initialization. – chris Dec 11 '12 at 07:04
  • I tried to do something like v[v1].edges.push_back(new Edges(v1, v2, v3)); and edges is defined as list edges; – JASON Dec 11 '12 at 07:06

2 Answers2

2

You can write a constructor for a struct as well in C++. A C struct is very limited, but in C++ there exists only 2 differences between struct and class.

  1. In class all members are by default private, in struct all members are by default public.
  2. Inheritance from struct defaults to public while class defaults to private

Thanks @gil_bz and @icepack

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
0

You need to create a parameterized constructor. Do it this way

struct Edge
{
    int weight;
    Vertex* v1;
    Vertex* v2;

    Edge(int a_weight, Vertex *a_v1, Vertex *a_v2)
    {
        weight = a_weight;
        v1 = a_v1;
        v2 = a_v2;
    }
};

Then create object like this:

Edge e(9, v1, v2);