Babak Abdolahi
Babak Abdolahi

Reputation: 6729

struct initialization in c++ error

I'm new to c++, I run the following code in visual studio c++

    struct bob
    {
       double a,b;      
       bob(double a,double b);
    }

    int main()
    {
        bob z(2.2,5.6);
        cout<<z.a<<endl;
        keep_window_open();
        return 0;
    }     

when I run this code, i get the following error:

Error 1 error LNK2019: unresolved external symbol "public: __thiscall bob::bob(double,double)" (??0bob@@QAE@NN@Z) referenced in function _main C:\drives\Comp-Mech\programming\V.S\C++\projects\E1\E1.obj E1

Upvotes: 1

Views: 978

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

You have provided a declaration for bob's constructor, but you have not given a definition. The definition gives the implementation of the constructor and says exactly what it should do. In this case, you likely want your constructor to assign its arguments to the object's member variables:

bob::bob(double a, double b)
{
  this->a = a;
  this->b = b;
}

I used assignment in the above code because you are more likely to be familiar with it. However, you should be aware of member initialization lists which allow you to initialize members directly:

bob::bob(double a, double b)
  : a(a), b(b)
{ }

This says to initialise the member a with the argument a and initialise member b with the argument b. It also avoids potentially expensive default initialization of members before assigning to them.

Upvotes: 3

john
john

Reputation: 8027

That's because you haven't written the code for bob::bob(double, double).

struct bob
{
   double a,b;      
   bob(double aa, double bb) a(aa), b(bb) {}
};

Upvotes: 1

piokuc
piokuc

Reputation: 26164

You need to implement constructor of your class bob:

 bob::bob(double a,double b) : a(a), b(b) {}

Upvotes: 5

Related Questions