-1

I have the following code in C++:

// This is the header file, test.h

typedef struct
{
   int a;
   int b;
} Numbers;

class Test
{
private;
   Numbers numbers_;
};

//This is the source file, test.cpp

#include "test.h"

Test::Test()
{}

Then I run lint on it, it says Warning 1401 member "numbers_" not initialized by constructor

I know how to initialize build in types in constructor, but how to initialize type like Numbers?

ratzip
  • 1,571
  • 7
  • 28
  • 53
  • Define a constructor for your struct `Numbers`, else using a initialization list in class `Test` doesn't help much. And then use the `Numbers` constructor in the initialization list of `Test` – DumbCoder Feb 20 '15 at 11:18
  • 3
    `typedef struct` – No. This makes absolutely no sense in C++. – Konrad Rudolph Feb 20 '15 at 11:18

4 Answers4

1

This is what you should do:

typedef struct numbers
{
   int a;
   int b;
   numbers()
   {
       a = 0;
       b = 0;
   }
} Numbers;

class Test
{
private:
   Numbers numbers_;
public:
    Test() : numbers_()
    {
    }
};

Note that:

  1. I named the struct as numbers, and then gave it a parameterless constructor.
  2. Also, there was a compile-time error in your code. The access specifers (private in your case) must be followed by a colon(:), not a semi-colon(;)
  3. I added a parameterless constructor for Test, and used initializer_list to call the constructor of Numbers.
Community
  • 1
  • 1
CinCout
  • 9,486
  • 12
  • 49
  • 67
0

Use a constructor for your struct.

You'll find some example here:

enter link description here

Community
  • 1
  • 1
McNets
  • 10,352
  • 3
  • 32
  • 61
  • It's always best to provide an answer and an explanation than just providing a link ( links might get changed ). – Arun A S Feb 20 '15 at 11:52
0

There are many ways to initialise class members.

You could aggregate-initialise it, giving values to each member:

Test::Test() : numbers_{42,53} {}

or you could value-initialise it, setting each member to zero:

Test::Test() : numbers_() {}

Alternatively, if you don't particularly need the Numbers class to be plain data, then you could let it initialise itself. You could give each member an in-class initialiser:

int a = 42;
int b = 53;

or you could give it a constructor:

struct Numbers  // the class needs a name to declare a constructor
{
    Numbers() : a(42), b(53) {}
    int a;
    int b;
};

Or, perhaps, you could ignore or disable the warning, but be careful to assign values to the uninitialised members before using them.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

If you don't want to write a custom constructor for the Numbers class you can also simply initialize the fields of the member object in your Test constructor:

Test::Test()
{
    numbers_.a = 0;
    numbers_.b = 0;
}
trenki
  • 7,133
  • 7
  • 49
  • 61