0

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.

Aman Rathore
  • 163
  • 9

2 Answers2

5

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
1

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;
}

Aman
  • 343
  • 2
  • 8
  • 3
    Your answer would be more useful if you explained WHY this code is needed. – Remy Lebeau Sep 21 '21 at 06:03
  • 3
    People who don't know what's wrong in OPs code will find it hard to spot the change you have made. Answers should be more about explaining problems and solutions than about providing ready-to-use code. – Lukas-T Sep 21 '21 at 06:06
  • Notice that `{}` (or even `= default;`) is risky here, as `a` would not be initialized, and so `num_3.print_number();` would lead to UB. – Jarod42 Sep 21 '21 at 08:44