Search code examples
c++constructorconstructor-overloading

Constructor Overloading Issue in C++


// Create a function which takes 2 point objects and computes the distance between those points
#include<iostream>
#include<cmath>
using namespace std;

class dist{
    int x, y;    
public:
    dist(int a , int b) {
        x = a;
        y = b;
    }
    dist();
    void caldistance(dist c1, dist c2) {
        // c1 = (8,9) & c2 (10, 7)
        // sqrt((10-8)^2 + (7-9)^2)
        // sqrt((c2.a-c1.a)^2 + (c2.b-c1.b)^2)
        int res = sqrt(pow((c2.x-c1.x),2)+pow((c2.y-c1.y),2));
        cout << "The Distance between the points ( " << c1.x << "," << c1.y << ")"  << "("<< c2.x << "," << c2.y << ")" << " is : " << res << endl;
    }
};

int main() {
    dist P(8,9);
    dist Q(11,6);
    dist G;
    G.caldistance(P,Q);
    
    return 0;
}

As soon as I am creating a new object G of class dist, according to me, it should call the function call distance of class dist but it is showing an error and the program is not getting executed

Error : /usr/bin/ld: /tmp/cc99m1Ky.o: in function main': try.cpp:(.text+0x5d): undefined reference to dist::dist()' collect2: error: ld returned 1 exit status


Solution

  • Define the constructor as

            dist():x(0),y(0) {}
    

    dist() is just a declaration, but you have not defined the construtor.