-2

Help me figure out how the line p1(10,15); works and From where p1 derive from as it was never declared. I am learning how constructor works i used this link link

#include<iostream>
using namespace std;

class Point
{
    private:
        int x, y;
    public:
    // Parameterized Constructor
    Point(int x1, int y1) 
    { 
     x = x1; 
     y = y1; 
    }

    int getX()       
    { 
        return x; 
    }
    int getY()
    { 
        return y;
    }
};

int main()
{
    // Constructor called
    Point p1(10, 15); 

    // Access values assigned by constructor
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

    return 0;
}
Farhad
  • 4,119
  • 8
  • 43
  • 66
Maddy
  • 17
  • 4

1 Answers1

2

When you make an instance of class Point, it automatically call constructor and do the assignment.

Point p1(10, 15);  

it's like this:

Point(10, 15) 
{ 
 x = 10; 
 y = 15; 
}

and you using 2 functions to get x,y :

cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
Farhad
  • 4,119
  • 8
  • 43
  • 66