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;
}
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();
Related
Is there a way to execute this code without using vectors?
Can this program be run without vectors in the polygon class?
If possible, how should I modify the code?
And is it right to write the copy constructor and the move constructor as it is now?
It's so hard to do C++ while playing Python. Help me.
Thank you.
Polygon.h
#pragma once
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
struct C2D {
double x, y;
};
class Polygon {
int point;
vector<C2D> arr;
public:
Polygon(int point_, C2D arr_[]) : arr(point_) {
point = point_;
memcpy(arr.data(), arr_, sizeof(C2D) * point);
};
Polygon(Polygon& p) : arr(p.point) {
point = p.point;
memcpy(arr.data(), p.arr.data(), sizeof(C2D) * point);
};
Polygon(Polygon&& p) {
point = p.point;
memcpy(arr.data(), p.arr.data(), sizeof(C2D) * point);
p.point = 0;
delete[]p.arr.data();
};
void print() const {
cout << "Polygon information" << endl;
for (int i = 0; i < point; i++) {
cout << i + 1<< "point" << " : " << arr[i].x << ", " << arr[i].y << endl;
}
cout << endl;
};
double area_result() {
double sum = 0;
for (int i = 1; i < point; i++) {
sum += ccw(arr[0].x, arr[i - 1].x, arr[i].x, arr[0].y, arr[i - 1].y, arr[i].y);
}
return fabs(sum);
}
static double ccw(double x1, double x2, double x3, double y1, double y2, double y3) {
double res = x1 * y2 + x2 * y3 + x3 * y1;
res += (-y1 * x2 - y2 * x3 - y3 * x1);
return res / 2;
}
};
main.cpp
int main() {
int point;
C2D* c2d;
cout << "point : ";
cin >> point;
cout << endl;
c2d = new C2D[point];
for (int i = 0; i < point; i++) {
cout << i + 1 << "x : ";
cin >> c2d[i].x;
cout << i + 1 << "y : ";
cin >> c2d[i].y;
cout << endl;
}
cout << endl;
Polygon p(point, c2d);
p.print();
cout << "Polygon area : " << p.area_result() << endl;
return 0;
}
Don't.
Vectors are one of those no-brainer improvements of C++ over C. Don't try to code around them, learn how to use them properly. You will see that many lines of code and many sources of headaches go away when you actually code C++.
Polygon.hpp
#ifndef POLYGON_HPP
#define POLYGON_HPP
#include <iostream>
#include <vector>
#include <cmath>
struct C2D
{
double x, y;
};
class Polygon
{
public:
Polygon( unsigned points_, std::vector<C2D> const & arr_ ) : points( points_ ), arr( arr_ ) {}
Polygon( Polygon & p ) : points( p.points ), arr( p.arr ) {}
Polygon( Polygon && p ) : points( p.points )
{
arr.swap( p.arr );
}
friend std::ostream & operator<<( std::ostream & out, Polygon const & p );
double area_result()
{
double sum = 0;
for ( unsigned i = 1; i < points; ++i )
{
sum += ccw( arr[0].x, arr[i - 1].x, arr[i].x, arr[0].y, arr[i - 1].y, arr[i].y );
}
return std::fabs( sum );
}
static double ccw( double x1, double x2, double x3, double y1, double y2, double y3 )
{
double res = x1 * y2 + x2 * y3 + x3 * y1;
res += ( -y1 * x2 - y2 * x3 - y3 * x1 );
return res / 2;
}
private:
unsigned points;
std::vector<C2D> arr;
};
#endif
main.cpp
#include "Polygon.hpp"
#include <vector>
#include <iostream>
std::ostream & operator<<( std::ostream & out, Polygon const & p )
{
out << "Polygon information" << std::endl;
for ( unsigned i = 0; i < p.points; ++i )
{
out << ( i + 1 ) << "point : " << p.arr[i].x << ", " << p.arr[i].y << std::endl;
}
out << std::endl;
return out;
}
int main()
{
int points;
std::vector<C2D> c2d;
std::cout << "points : ";
std::cin >> points;
c2d.reserve( points );
for (int i = 0; i < points; i++) {
C2D coord;
std::cout << i + 1 << "x : ";
std::cin >> coord.x;
std::cout << i + 1 << "y : ";
std::cin >> coord.y;
c2d.push_back( coord );
}
Polygon p( points, c2d );
std::cout << p << "Polygon area : " << p.area_result() << std::endl;
return 0;
}
Your code is using vector exactly like a C style array, so you can replace it with such an array with minimum changes.
In fact, it will make your code simpler to read, since you will not be misusing a C++ object like a C variable.
class Polygon {
int point;
C2D *arr;
public:
Polygon(int point_, C2D arr_[]) {
point = point_;
arr = new C2D[point];
//you should check here allocation is successful
memcpy(arr, arr_, sizeof(C2D) * point);
};
Polygon(Polygon& p) {
point = p.point;
arr = new C2D[point];
memcpy(arr, p.arr, sizeof(C2D) * point);
};
Polygon(Polygon&& p) {
point = p.point;
arr = p.arr;
p.point = 0;
p.arr = null;
};
//you will need to add a destructor to clean up memory
~Polygon() {
delete [] arr;
}
};
That said, as the comments suggest, this is a bad practice.
If you have some constraints, such as a limited C++ environment lacking a vector implementation, a need to interface your code with another language / runtime, or homework requirement, you should add them to your question for suggestions on better solution.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
#include <iostream>
class Point {
private:
int* x; int y;
public:
Point(int x1, int y1) {
int* x = new int;
*x = x1 ;
y = y1;
}
int* getX() { return x; }
void setX(int* p) { x = p; }
int getY() { return y; }
};
int main()
{
Point* p1 = new Point(10, 15);
Point* p2 = new Point(20, 25);
p2->setX(p1->getX());
std::cout << "p1.x = " << p1->getX() << ", p1.y = " << p1->getY() << std::endl;
std::cout << "p2.x = " << p2->getX() << ", p2.y = " << p2->getY() << std::endl;
delete p1;
delete p2;
return 0;
}
What is the problem with allocation space in the constructor ?
You're redeclaring the local.
Instead of
int* x = new int;
do
x = new int;
Here is working code with little modification.
#include <iostream>
using namespace std;
class Point {
private:
int* x; int y;
public:
Point(int x1, int y1) {
x = new int;
*x = x1 ;
y = y1;
}
int* getX() { return x; }
void setX(int* p) { x = p; }
int getY() { return y; }
};
int main()
{
Point* p1 = new Point(10, 15);
Point* p2 = new Point(20, 25);
p2->setX(p1->getX());
std::cout << "p1.x = " << *p1->getX() << ", p1.y = " << p1->getY() << std::endl;
std::cout << "p2.x = " << *p2->getX() << ", p2.y = " << p2->getY() << std::endl;
delete p1;
delete p2;
return 0;
}
Output
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 25
Is this you were expecting
There are several drawbacks in the code.
For starters in this constructor
Point(int x1, int y1) {
int* x = new int;
*x = x1 ;
y = y1;
}
the data member x is not initialized. The constructor deals with a local variable x declared in the body of the constructor
int* x = new int;
You could write the constructor like
Point( int x1, int y1 ) : x( new int( x1 ) ), y( y1 ) {}
The function setX should make a deep copy of the passed pointer and free the already allocated memory pointer to which is stored in the data member x.
void setX(int* p) { delete x; x = new int( *p ); }
Also you need at least a destructor. Otherwise the memory pointed to by the pointer x will not be deleted.
~Point() { delete x; }
Also it is desirable to define the copy assignment operator and the copy constructor.
your program has a memory leak because the "new int" must be free alos. But the big error is that when you do :
p2->setX(p1->getX());
You overwrite the address of P2.x and you will no longer be able to release it because you have lost its original adress.
even if you delete P2->x it will cause a double release of P1.x adresse
I have a base class Point with 3 variables I want derived as Body attributes. I want to initialize a point and use it to initialize a body object. Here is what I have so far:
#include <iostream>
using namespace std;
class Point {
public:
double x, y, z;
// default constructor
Point(): x(0), y(0), z(0){
};
// intialization constructor
Point(double x, double y, double z){
x = x;
y = y;
z = z;
}
// copy constructor
Point(const Point &point){
x = point.x;
y = point.y;
z = point.z;
}
void print_point(){
cout << "x = "<< x << " y = " << y << " z = " << z << endl;
}
};
class Body: public Point{
public:
double mass;
// default constructor
Body(): Point(0, 0, 0), mass(0){
};
// intialization constructor
Body(const Point& point, double mass): Point(point.x, point.y, point.z){
mass = mass;
}
// copy constructor
Body(const Body &body): Point(body){
mass = body.mass;
}
void print_body(){
cout << "x = "<< x << " y = " << y << " z = " << z << " mass = " << mass << endl;
}
};
int main() {
Point p(1., 2., 3.);
p.print_point();
Body b(p, 65.);
b.print_body();
return 0;
}
When I compile and run this, I get:
x = 0 y = 0 z = 6.95312e-310
x = 2.25081e-314 y = 0 z = 0 mass = 0
When I am expecting to get:
x = 1 y = 2 z = 3
x = 1 y = 2 z = 3 mass = 65
It's like the variables are being reset by the default constructors, and I don't know what's causing this.
You should change the assignment inside the constructor body from
x = x;
y = y;
z = z;
to
this->x = x;
this->y = y;
this->z = z;
Inside the constructor's body, the parameter's name hides the data member's name. e.g. x = x; just assigns the parameter x to itself, doesn't assign the data member x. The class Body has the same issue.
The better way would be initializing the data members with member initializer list, (btw it doesn't have such name hiding issue). e.g.
Point(double x, double y, double z) : x(x), y(y), z(z) {}
I get a weird error when I try and compile the following code:
I need to use structs (I was taught classes with the struct keywor, and am trying to learn it that way. I also need to put the function definitions outside the struct block.
#include <iostream>
#include <string>
using namespace std;
struct Box {
int l;
int w;
int area();
Box();
Box(int a, int b);
Box operator+(const Box a, const Box b);
};
Box::Box() {
l = 0;
w = 0;
}
Box::Box(int a, int b) {
l = a;
w = b;
}
Box Box::operator+(const Box a, const Box b) {
Box box(a.l + b.l, a.w + b.w);
return box;
}
int Box::area() {
return l * w;
}
int main() {
Box a(1, 2);
Box b;
b.l = 3;
b.w = 4;
Box c = a + b;
cout << "Total area is: " << a.area() << " + " << (b.area) << " = " << (c.area) << endl;
}
Could someone help me out? Thanks
operator+ which belongs to the class/struct should receive only one parameter of type Box (from the right side of +) which should be added to the current object (from the left side of +):
Box Box::operator+(const Box& a) {
Box box(a.l + l, a.w + w);
return box;
}
Also in the cout line it should be b.area() and c.area() instead of (b.area) and (c.area).
Here's your code modified a bit. I had to put the operator overload into the struct due to the compiler not using NRVO (See here)
#include <iostream>
#include <string>
using namespace std;
struct Box {
int l;
int w;
Box();
Box(int a, int b);
int area();
Box operator+(const Box a)
{
return Box(a.l + l, a.w + w);
}
};
Box::Box() {
l = 0;
w = 0;
}
Box::Box(int a, int b) {
l = a;
w = b;
}
int Box::area() {
return l * w;
}
int main() {
Box a(1, 2);
Box b;
b.l = 3;
b.w = 4;
Box c = a + b;
cout << "Total area is: " << a.area() << " + " << (b.area()) << " = " << (c.area()) << endl;
}
Result:
Total area is: 2 + 12 = 24
I am trying to return a boolean value using a C++ class. It needs to be able to check whether circle A is the same size as circle B using an overload operator > which I have added as a public member in the class. In my int main it always seems to return false even when the circles are the same size.
Thanks, in advance.
Circle class:
#include <iostream>
#include <cmath>
using namespace std;
//creating a constant pi that can't be changed
const double pi = 3.14159265;
class Circle
{
//defining the private memeber variables
private:
double radius, xpos, ypos;
//defining the public member variables
public:
//creating a constructor that takes all of the variables
Circle(double r, double xposition, double yposition) {
radius = r;
xpos = xposition;
ypos = yposition;
}
//creating a constructor that takes just the radius
Circle(double r) {
radius = r;
xpos = 0;
ypos = 0;
}
//creating a contructor that initialised everything to 0
Circle() {
radius = 0;
xpos = 0;
ypos = 0;
}
//defining the functions for radius, X-position, Y-position and area
double getRadius() {return radius;}
double getX() {return xpos;}
double getY() {return ypos;}
double getArea() {return pi*radius*radius;}
//creating an overaload operator + to add the various properties of a circle together
Circle operator+(Circle C) {
radius = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area
xpos = (this->getX() + C.getX()) / 2.; //calculating the half way x position
ypos = (this->getY() + C.getY()) / 2.; //calculating the half way y position
return Circle(radius, xpos, ypos);
}
//created an overload operator << that outputs information about the circle in a consistent manor
friend ostream& operator<<(ostream& os, Circle C) {
return os << "radius = " << C.getRadius() << " at (x,y) = (" << C.getX() << "," << C.getY() << ")";
}
bool operator>(Circle C) {
if (this->getRadius() > C.getRadius()) {
return true;
}
else {
return false;
}
}
};
Int main ()
#include "Circle.hpp"
using namespace std;
int main()
{
//defining the circles A and B
Circle A(4.0,2.0,1.0);
cout << "Circle A: " << A << endl;
Circle B(4.0,5.0,6.0);
cout << "Circle B: " << B << endl;
//Adds A and B using the overload operator +
Circle C = A + B;
//Outputs the formatted text using the overload operator <<
cout << "Circle C: " << C << endl;
bool test;
Circle D(4.0,2.0,1.0);
if (A > D) {
test = false;
}
else if (D > A) {
test = false;
}
else {
test = true;
}
cout << boolalpha << test << endl;
return 0;
}
A.r is 4.0. D.r is also 4.0. Neither D > A nor A > D is true. > checks for real greater than. If you want to have greater-or-equal use >= instead.
When you do the following you are changing the value of A's radius
Circle C = A + B
"In my int main it always seems to return false even when the circles are the same size"
It will surely return false when circle are of same size as your condition is:-
if ( this->getRadius() > C.getRadius() )
return true;
everything other than this would return false. If you want to return true when your circle are of same size then make it:-
if ( this->getRadius() < C.getRadius() )
return false;
else
return true;
EDITED IN RESPONSE TO COMMENT:-
Then probably you can use enum if want to to test three different scenarios:-
if ( this->getRadius() > C.getRadius() )
return ENUM_GREATER;
else if ( this->getRadius() == C.getRadius() )
return ENUM_EQUAL;
return ENUM_LESSER;
Your operator+ modifies the left-hand operand. So, this line modifies A :
Circle C = A + B;
(including the radius member). So, by the time you compare A to D, A's radius is no longer 4.0.
The operator+ can be modified as follows to fix this :
Circle operator+(const Circle& C) const {
double r = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area
double x = (this->getX() + C.getX()) / 2.; //calculating the half way x position
double y = (this->getY() + C.getY()) / 2.; //calculating the half way y position
return Circle(r, x, y);
}