Alex
Alex

Reputation: 129

defining constructor in a struct

trying to see how structs and constructors work in header, implementation, and main files. Using constructor and default constructor. I get compilation error in mains.cpp of "undefined reference to 'numbers::numbers()'

In test.h I have:

#ifndef H_TEST
#define H_TEST

struct numbers{

   int a;
   int b;
numbers();

numbers(int x, int y);

};
#endif

In Numbers.cpp I have:

#include "test.h"

 numbers::numbers()
  {
     a=0;
     b=0;
  }
  numbers::numbers(int x, int y)
  {
      a=x;
      b=y;
  }

In mains.cpp I have:

 #include<iostream>
 #include "test.h"
 using namespace std;

 numbers num;//compilation error occurs here
 int main()

{





 return 0;
 }

Upvotes: 0

Views: 554

Answers (2)

Jonathan Sharman
Jonathan Sharman

Reputation: 636

The problem is that you're default-constructing num and not reassigning it.

numbers num; // Constructs a numbers object with a = 0, b = 0 and stores it in num.
int main()
{
    numbers(3,5); // Constructs a numbers object with a = 3, b = 5.
                  // The object is discarded after the constructor call finishes.

    cout<<num.a; // Prints a from the global variable num.

    return 0;
}

I think you intended to reassign num:

numbers num; // num is default-constructed to a = 0, b = 0, as before.
int main()
{
    num = numbers(3,5); // num now holds a = 3, b = 5.

    cout<<num.a; // Prints 3, as expected.

    return 0;
}

Side notes: You generally should avoid non-const global variables. Also, when possible, initialize variables in the same line you declare them to avoid assigning the data members twice (doesn't really matter for very small objects like this one).

Edit: I didn't notice the problem that QuantumMechanic pointed out. You'll have to fix both errors for the program to work as you expect.

Upvotes: 3

QuantumMechanic
QuantumMechanic

Reputation: 13946

Looks like you're declaring inline constructors in the header file by putting in function bodies (albeit empty function bodies) for the constructors.

I would expect that in files that include the header, when the compiler sees the inline definitions it will use those and so never generate a symbol to be linked with the definitions in the .cpp file and therefore the definitions in the .cpp file will not be called.

Try deleting the empty function bodies in the header.

Upvotes: 3

Related Questions