Home > Software design >  Undefined reference to constructor problem
Undefined reference to constructor problem

Time:09-22

See the below-given code

#include <iostream>
using namespace std;

class Number
{
    int a;

public:
    Number();

    Number(int num_1) {
        a = num_1;
    }

    void print_number(void) { cout << "Value of a is " << a << endl; }
};

int main()
{
    Number num_1(33), num_3;
    Number num_2(num_1);

    num_2.print_number();
    return 0;
}

In the above code, I am having 2 constructors in the same class but when compiling it,gives me the error

ccnd0o9C.o:xx.cpp:(.text 0x30): undefined reference to `Number::Number()'
collect2.exe: error: ld returned 1 exit status  

Can anyone solve this problem? and I still need the 2 constructors but without replacing num_3 with num_3() the main function.

CodePudding user response:

In your class, you have declared the default constructor, but you have not defined it.

You can default it (since C 11) and you will be good to go:

Number() = default;

Otherwise:

Number() {}

As from @TedLyngmo liked post, both will behave the same, but the class will get different meaning as per the standard, though. More reads here: The new syntax "= default" in C 11


@Jarod42's Comment as side notes: The default constructor make sense when it provide a default value to the member a. Otherwise it will be uninitialized (indeterminate value) and reading them will cause to UB.

CodePudding user response:

Use this code

#include <iostream>

using namespace std;
class Number
{
    int a;

public:
    Number(){};
    Number(int num_1)
    {
        a = num_1;
    }

    void print_number(void) { cout << "Value of a is " << a << endl; }
};

int main()
{
    Number num_1(33), num_3;

    Number num_2(num_1);
    num_2.print_number();

    return 0;
}

  • Related