Home > database >  How to properly define a constructor C
How to properly define a constructor C

Time:10-16

I'm new to learning c and I have been experiencing a odd error that I can't find the solution for (even on stackoverflow).

Here is the code below.

 struct Date {
 void add_day(int n);
 int d,m,y;
 Date(int d,int m,int y);
};



int main()
{
Date today {3,4,5};
cout << today.d;

}

All I want is to create a simple date object using a constructor however I get a undefined reference, more specifically this error: undefined reference to `Date::Date(int, int, int)'.

If this is relevant, the compiler im using is g version 12.2.0 from MSYS2. I am coding on VSCode.

Im learning via Programming and Principles written by Bjarne Stroup. I am a complete beginner and apologize for asking such a basic question.

Thank you for taking the time to read this question.

CodePudding user response:

The main reason is that compiler does not know where is the function body of the construction function Date::Date(int d,int m,int y);

Solution

You can either implement its function body to replace ";" sign. Or you can implement its function body out side the struct.

Here is a demo with full code:


struct Date {
public:  // public is default for struct
    Date(int _d,int _m,int _y):d(_d){  // did init m is also ok
        y=_y;  // init variable inside the body is also ok
    }
    Date();  // second case, body is outside
void add_day(int n);  // did not implement, ok if not been called.
    int d,m,y;
};

Date::Date():d(0), m(0){
    y=0;
}

int main(){
  Date today(3,4,5);  // this triggers Date(int d,int m,int y)
  Date today2;  // this triggers Date()
  cout << today.d << endl;
  return 0;
}
  • Compile and Run

    g   -Wall demo.cpp
    ./a.out
    
  • Output

    3
    

p.s. Up-Vote is generous and kind. It also helps and supports the author, if the solution is useful.

  •  Tags:  
  • c
  • Related