JASON
JASON

Reputation: 7491

How to create a struct and initialize it at the same time?

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!

Upvotes: 0

Views: 121

Answers (2)

Karthik T
Karthik T

Reputation: 31952

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

Upvotes: 2

Mian Zeshan Farooqi
Mian Zeshan Farooqi

Reputation: 311

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);

Upvotes: 0

Related Questions