smilingbuddha
smilingbuddha

Reputation: 14660

C++ problem in declaring a struct

I am unable to see what is wrong in the following (very contrived) code. It might be the way I have declared a size 2 vector inside the mystruct. But isn't that how we declare a vector of size 2 whose contents we have yet to initialize?

struct mystruct
{
  int a;
  int b;
  vector<double> c(2);    };

   int main(int argc, char *argv[])
{
  mystruct test;
  (test.c)[0]=3.4;
  (test.c)[1]=1.8;
  return 0;    }

The compiler is throwing me the following error message:

g++ -Wall simple.cpp

simple.cpp:18: error: expected identifier before numeric constant

simple.cpp:18: error: expected ‘,’ or ‘...’ before numeric constant

simple.cpp: In function ‘int main(int, char**)’:

simple.cpp:32: error: invalid types ‘[int]’ for array subscript

simple.cpp:33: error: invalid types ‘[int]’ for array subscript

Upvotes: 3

Views: 1730

Answers (5)

Benjamin Bannier
Benjamin Bannier

Reputation: 58556

You cannot initialize mystruct::c in the class definition, this has to be done in the constructor.

struct mystruct {
  mystruct() : c(2) { }
  vector<double> c;
};

Upvotes: 6

Kerrek SB
Kerrek SB

Reputation: 476950

That's just not how C++ works.

When you declare a class, you cannot specify constructors for member objects (with the exception of static constant integrals). Instead, you must specify the constructor arguments for members in the class's constructor initializer list:

class Foo
{
  std::vector<int> v;
public:
  Foo() : v(2) { }
};

Upvotes: 2

user380041
user380041

Reputation:

You need a constructor if you want to initialize the vector (call vector's constructor)

struct mystruct
{
  int a;
  int b;
  vector<double> c;

  mystruct():
    c(2)
    {

    }
};

Upvotes: 2

James
James

Reputation: 25513

This isn't a valid declaration:

vector<double> c(2);

You probably want:

vector<double> c;

Then, in main:

int main(int argc, char *argv[])
{
     mystruct test;
     test.c.push_back(3.4);
     test.c.push_back(1.8);
     return 0;
}

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 992807

You're trying to construct c in your struct declaration. Vectors only have a size upon construction. Try:

struct mystruct {
    mystruct(): c(2) {}
    int a;
    int b;
    vector<double> c;
};

The mystruct() constructor uses the member initialisation syntax c(2) to construct c.

Upvotes: 2

Related Questions