Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct constructor

I tried to create my own structure. So I wrote this piece of code.

struct node
{
    int val, id;
    node(int init_val, int init_id)
    {
        val = init_val;
        id = init_id;
    }
};

node t[100];

int main()
{
...
}

I tried to compile my program. But I got an error:

error: no matching function for call to 'node::node()'
note: candidates are:
note: node::node(int, int)
note: candidate expects 2 arguments, 0 provided
note: node::node(const node&)
note: candidate expects 1 argument, 0 provided
like image 906
PepeHands Avatar asked Nov 02 '13 14:11

PepeHands


People also ask

Can a struct have a constructor C?

Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

What is a struct constructor?

A structure called Struct allows us to create a group of variables consisting of mixed data types into a single unit. In the same way, a constructor is a special method, which is automatically called when an object is declared for the class, in an object-oriented programming language.

Can a struct have two constructors?

A structure type definition can include more than one constructor, as long as no two constructors have the same number and types of parameters.

Are there constructors in struct?

struct can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types. struct cannot include a parameterless constructor or a destructor. struct can implement interfaces, same as class. struct cannot inherit another structure or class, and it cannot be the base of a class.


2 Answers

node t[100];

will try to initialise the array by calling a default constructor for node. You could either provide a default constructor

node()
{
    val = 0;
    id = 0;
}

or, rather verbosely, initialise all 100 elements explicitly

node t[100] = {{0,0}, {2,5}, ...}; // repeat for 100 elements

or, since you're using C++, use std::vector instead, appending to it (using push_back) at runtime

std::vector<node> t;
like image 92
simonc Avatar answered Oct 12 '22 07:10

simonc


This will fix your error.

struct node
{
int val, id;
node(){};

node(int init_val, int init_id)
{
    val = init_val;
    id = init_id;
}
};

You should declare default constructor.

like image 33
iDebD_gh Avatar answered Oct 12 '22 07:10

iDebD_gh