C++ Passing an Object to a Member Function - c++

For a homework assignment we are asked to create two classes: a MyPoint class and a ThreeDPoint class.
Here is my MyPoint class:
#pragma once
#include <math.h>
class MyPoint
{
private:
double x, y;
public:
MyPoint()
{
x = y = 0;
}
MyPoint(double x, double y)
{
this->x = x;
this->y = y;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
double distance(MyPoint pointB)
{
return sqrt((x - pointB.x) * (x - pointB.x)
+ (y - pointB.y) * (y - pointB.y));
}
};
Here is my ThreeDPoint class:
#pragma once
#include "MyPoint.h"
class ThreeDPoint : public MyPoint
{
private:
double z;
public:
ThreeDPoint() // : MyPoint()
{
z = 0;
}
ThreeDPoint(double x, double y, double z) : MyPoint(x, y)
{
this->z = z;
}
double getZ()
{
return z;
}
double distance(ThreeDPoint pointB) // function overloading
{
// x and y are private not protected
return sqrt((getX() - pointB.getX()) * (getX() - pointB.getX())
+ (getY() - pointB.getY()) * (getY() - pointB.getY())
+ (getZ() - pointB.getZ()) * (getZ() - pointB.getZ()));
}
};
And here is main:
#include <iostream>
#include "SignatureBlock.h"
#include "MyPoint.h"
#include "ThreeDPoint.h"
int main()
{
SignatureBlock myBlock;
std::cout << myBlock.toString();
MyPoint pointA(1, 2);
MyPoint pointB(4, 2.5);
std::cout << pointA.distance(pointB) << '\n';
ThreeDPoint point_a(0, 0, 0);
ThreeDPoint point_b(10, 30, 25.5);
std::cout << point_a.distance(point_b) << '\n';
return 0;
}
This code works fine. It is able to calculate the distance between two points in both 2-dimensional and 3-dimensional space. However, in the homework instructions for the ThreeDPoint class, the book says to create
"A constant get function that returns the z value"
and
"A constant distance(const MyPoint&) function to return the distance between this point and the other point in three-dimensional space."
My question is what do they mean by "A constant get function..." and "A constant distance(const MyPoint&) function..."? I understand that you can put const after a function declaration to prevent the function from changing any class members, but why is this necessary here?
Also, why would I pass const MyPoint& to the distance function rather than a ThreeDPoint object? After all we're trying to find the distance between two ThreeDPoints. I read that if you have a parent object parameter in the member function declaration any child of that parent can also be passed to the function, so maybe that has something to do with it.
Lastly, isn't the distance(const MyPoint&) in the instructions missing a name for the MyPoint& object? I did try to type this in and the compiler doesn't mind, but how would I access the members of the object being passed in?
Edit: Also, what purpose does the & serve?
Most importantly, how would I re write my code to follow exactly what the instructions state?
Thanks for reading and thank you for any suggestions anyone might have.

If you live in a world where there are no const objects, it's never necessary to mark methods const. However, it is a good idea. Using const pointers and references is a very good practice when you don't need to change members of an object, and it can help you find design flaws when your program gets bigger.
It's also a good practice to pass references to objects, because passing a reference is usually faster than passing a copy of the object. (It's also in this context that you'll use const references: it tells the caller that you want the object by reference because it's faster, not because you want to change it.)
It's legal to omit argument names, but it has the obvious consequence that you won't be able to use them in your function. It's also a common notation because compilers get rid of argument names when they create function signatures, so you'll often see error messages that look like distance(const MyPoint&) instead of distance(const MyPoint& point).
I can't help you about why they want a const MyPoint& for the ThreeDPoint class. My best guess is that they want you to assume the z component of that point is 0.

Related

Cannot figure out how to calculate radius of the circle in the given code

I need to calculate the radius of the circle in the code.
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
float radius;
const float PI=3.14;
public:
Circle(float radius){
}
Circle getRadius()
{
return radius;
}
Circle setRadius(float radius)
{
this->radius = radius / PI;
return radius;
}
float Area()
{
return radius*radius*PI;
}
float Perimeter()
{
return 2*radius*PI;
}
int equal()
{
return Area()==Perimeter();
}
};
int main() {
float r;
cin >> r;
Circle c(r);
cout << c.Perimeter() << endl;
cout << c.Area() << endl;
cout << c.equal() <<endl;
return 0;
}
i tried to use pointers but i cannot figure it out.
In
Circle(float radius){
}
a parameter with the same name as a member variable is not that member variable. Instead, it shadows the member variable, effectively replacing it unless you know where to look. Passing a value into a parameter named radius will not change the value of the member variable named radius, and this leaves the member radius uninitialized.
This means that
float Perimeter()
{
return 2*radius*PI;
}
and the other functions, excluding setRadius, operate on an uninitialized variable and the results will be undefined.
A possible solution is to ensure the member radius is initialized to the value of the parameter radius.
You cannot simply
Circle(float radius){
radius = radius;
}
because there is only one radius, the member has been shadowed, so the parameter radius assigns its value to itself. This is legal code so it compiles, but often the compiler will issue a warning.
Instead use
Circle(float radius) : radius(radius) {
}
This makes use of the Member Initializer List, one of the most important (and seemingly least-taught) features of the C++ programming language. It allows you to safely reuse the term radius because the first radius must be the member radius.
You could also
Circle(float radius) {
this->radius = radius;
}
to explicitly use the member radius, but for more complicated members this approach can be inefficient. All member variables and base classes are initialized before entering the body of the constructor. Afterward the best you can do is assign. This means the member will be default-initialized (if a default constructor exists; if it doesn't you must use the member initializer list), then a temporary variable must be constructed and this temporary is then assigned to the member. potentially a lot of extra work for no benefit.
Side note:
Keep an eye on the this->radius = radius / PI; in setRadius. It is unusual and probably a bug.

C++ Accessing operator function in inherited class

I am currently writing an application where I use the Eigen-Library for complex 3D-Math. Because I needed distinct point and vector classes, my point3d-class looks like this:
class point3d : public Eigen::Vector4d
{
public:
point3d(){}
point3d(double x, double y, double z) : Eigen::Vector4d(x, y, z, 1) {}
void fromString(std::string input);
};
Now I want to create a member function of this class that allows me to parse lines of OBJ-files which look like this:
v 2.8 0.52 10.18
as such point. This is how I intend to design my parsing function
void point3d::fromString(std::string input)
{
char* buf = strdup(input.c_str());
if (strtok(buf, " ") == "v")
{
;
strtok(buf, " ");
this-x = std::stod(strtok(buf, " "));
this->y = std::stod(strtok(buf, " "));
this->z = std::stod(strtok(buf, " "));
}
}
My problem is that Eigen does not allow me to access the data stored in Vector4d as this->x, this-y, this->z and so on. Instead, you'd usually access it as Vector4d v; v[0], v[1], v[2] etc. I think the way it does that is by using a
double Eigen::Vector4d::operator[](unsigned int index){...}
function.
I don't know how exactly one would access that data in a derived class. What do I have to do to access this data within that function so that I can write to the x, y, z values?
You can do
(*this)[0]
and so on in order to call the base class operator[].
x, y, z aren't member variables of Eigen::Vector4d, but methods. You can access them from your derived class using this->x() etc (or Vector4d::x()). What also works is (*this)[0] or (*this)(0). If you need to access x(), y(), z() frequently in your class, you could write once:
using Vector4d::x;
using Vector4d::y;
using Vector4d::z;
And afterwards access them using just x(), y(), z(). However, this may cause some shadowing conflicts (if you name local variables the same way).

How to use & modifier on a parameter in a C++Function call

I've been given a task for my cpp homework, the task is long and has many more functions that this, but I am stuck at the beggining. What I am trying to do here is just write out the point that is given on the screen.
#include <iostream>
using namespace std;
class Point {
public:
double x, y;
Point(){
x=0.0;
y=0.0;
};
Point(double x,double y){
this -> x = x;
this -> y = y;
}
void print() {
cout << "(x,y) = ("<< x <<","<< y <<")"<<endl;
}
};
class Triangle {
public:
Point A;
Triangle(const Point& p1){
A.x = p1.x;
A.y = p1.y;
}
void print1(){
cout << "A(x,y) = ("<< A.x <<","<< A.y <<")"<<endl;
}
};
int main(){
Triangle A{1.0,2.0};
A.print1();
return 0;
}
What my thinking here is, I have a class named Point and it is made of two variables x and y, class Triangle in the task has 3 points, but I am using just one for simplicity, it has a point that is from class Point (so it should have x and y coordinates) and a constructor that has a point from class Point also. I was thinking just to link their x and y coordinates and to print them out. But it doesn't work like that, can you help me. I have more code from the task if you need, and code from our lessons. Thank you.
Triangle(const Point& p1) accepts a const reference to a Point. A reference is an alias to an existing variable. In this case rather than copying in a Point, the Triangle constructor receives the Point itself. The const is important because it is a promise that the Point will not be modified inside by Triangle's constructor. This allows you to pass in a reference to a temporary Point that otherwise would not be around long enough for modification to be meaningful and is rejected by the compiler to prevent possible errors.
Triangle A{1.0,2.0};
will attempt to make Triangle from two floating point values. Triangle needs a reference to a Point, so you must make that Point first.
Triangle A{ {1.0,2.0} };
^ ^
| Construct a temporary Point from 2 floating point numbers
Triangle constructor arguments: one Point
Unrelated improvement: Use the Member Initializer List
Triangle(const Point& p1): A{p1}{
}

How can I make a variable always equal to the result of some calculations?

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?
I mean something like that won't work, right?
int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;
If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.
Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.
Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.
You mean something like this:
class Z
{
int& x;
int& y;
public:
Z(int& x, int& y) : x(x), y(y) { }
operator int() { return x + y; }
};
The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:
int x, y;
Z z(x, y);
std::cin >> x >> y;
if(std::cin) // otherwise, IO error! (e. g. bad user input)
std::cout << z << std::endl;
Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...
You can get close to this with by using a lambda in C++. Generally, when you set a variable like
int x;
int y;
int z{x + y};
z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.
If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like
int x;
int y;
auto z = [&](){ return x + y; };
cin >> x;
cin >> y;
cout << z();
and now z() will have the correct value instead of the uninitialized garbage that the original code had.
If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like
auto z = [&](){ static auto cache_x = x;
static auto cache_y = y;
static auto cache_result = x + y;
if (x != cache_x || y != cache_y)
{
cache_x = x;
cache_y = y;
cache_result = x + y;
}
return cache_result;
};
The closest you probably can get is to create a functor:
#include <iostream>
int main() {
int x;
int y;
auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y
while(true) {
std::cin >> x;
std::cin >> y;
std::cout << z() << "\n";
}
}
There are two chief techniques:
Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).
Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).
The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.
This sounds like the XY problem (pun intended).
From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.
Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".
Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:
class Player {
std::vector<int> inventory;
int cash;
public:
int inventory_total();
int net_worth();
}
//adds up total value of inventory
int Player::inventory_total() {
int total = 0;
for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
total += *it;
}
return total;
}
//calculates net worth
int Player::net_worth() {
//we are using inventory_total() as if it were a variable that automatically
//holds the sum of the inventory values
return inventory_total() + cash;
}
...
//we are using net_worth() as if it were a variable that automatically
//holds the sum of the cash and total holdings
std::cout << player1.net_worth();
I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.
That would be very annoying and error prone if you forgot to call the function somewhere.
In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.
You create a function for that.
You call the function with the appropriate arguments when you need the value.
int z(int x, int y)
{
return (x + y);
}
int x;
int y;
// This does ot work
// int z{x + y};
cin >> x;
cin >> y;
cout << z(x, y);
You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:
DEMO
int main()
{
int x;
int y;
const auto z = [&x, &y](){ return x+y; };
std::cin >> x; // 1
std::cin >> y; // 2
std::cout << z() << std::endl; // 3
std::cin >> x; // 3
std::cin >> y; // 4
std::cout << z() << std::endl; // 7
}
So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
I would suggest doing that via class:
class foo {
int x;
int y;
int z;
void calculate() { z = (x + y) / 2; }
friend istream& operator >>(istream& lhs, foo& rhs);
public:
void set_x(const int param) {
x = param;
calculate();
}
int get_x() const { return x; }
void set_y(const int param) {
y = param;
calculate();
}
int get_y() const { return y; }
int get_z() const { return z; }
};
istream& operator >>(istream& lhs, foo& rhs) {
lhs >> rhs.x >> rhs.y;
rhs.calculate();
return lhs;
}
This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:
class foo {
int x;
int y;
int z;
bool dirty;
void calculate() { z = (x + y) / 2; }
friend istream& operator >>(istream& lhs, foo& rhs);
public:
void set_x(const int param) {
x = param;
dirty = true;
}
int get_x() const { return x; }
void set_y(const int param) {
y = param;
dirty = true;
}
int get_y() const { return y; }
int get_z() const {
if(dirty) {
calculate();
}
return z;
}
};
istream& operator >>(istream& lhs, foo& rhs) {
lhs >> rhs.x >> rhs.y;
rhs.dirty = true;
return lhs;
}
Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:
foo xyz;
cin >> xyz;
cout << xyz.get_z();
You can get what you're asking for by using macros:
{
int x, y;
#define z (x + y)
/* use x, y, z */
#undef z
}
The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.
Although a class with a custom operator int would work in a lot of cases ... hmm.
What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.
You could write a class that encapsulates its state to update either when mutated or return the right result when requested :
#include <iostream>
template<typename T, typename U, typename V>
class DynamicCalc
{
public:
DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
_func(func)
, _memberOne(memberOne)
, _memberTwo(memberTwo)
{
}
void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
auto Retrieve() { return _func(_memberOne, _memberTwo); }
U GetMemberOne() { return _memberOne; }
V GetMemberTwo() { return _memberTwo; }
private:
T _func;
U _memberOne;
V _memberTwo;
};
int main() {
auto func = [](int x, int y) {
return x + y;
};
DynamicCalc<decltype(func), int, int> c(func, 3, 5);
c.SetMemberOne(5);
std::cout << c.Retrieve();
}
In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.
Ok, let me at last write the right and only true answer to your stated question:
You can't.
You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.
So what can be done?
As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.
Depending on a use case, you may:
Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.
For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.
Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.
Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.
Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.

c++ class members functions: how to write these functions?

In my Object Oriented c++ course, we have to write this class that I have put below.
Point
class Point{
public:
Point( double x = 0, double y = 0 );
double getX() const;
double getY() const;
Point & setX( double x ); // mutator, returning reference to self
Point & setY( double y );
const Point & output() const;
double distance( const Point & other ) const;
private:
double xPoint, yPoint;
}; // class Point
my question is...I can't find any information on how the functions setX, setY, and output should work. They are the same type as the class itself and I have written what I would expect them to look like below. Can anyone tell me what I am doing wrong and maybe some more specifics of how these functions are working?
The setX function should change xPoint in the object, the setY should do the same for the yPoint and output should simply output them.
Point & Point::setX( double x )
{
xPoint = x;
}
Point & Point::setY( double y )
{
Ypoint = y;
}
const Point & Point::output() const
{
cout << xPoint << yPoint;
}
Just add a return *this; at the end of your setX and setY: you are returning a reference to your object, so that for example you can do: p0.setX(1.23).setY(3.45), with of course p0 an instance of Point. In the output function, put a separator between xPoint and yPoint, like a space. You say They are the same type as the class itself: don't confuse a variable type with the type returned by a function/method: the method setX, setY and output return a reference to an instance of the class to which they belong. Note that the reference returned by output is const, so you can do:
p0.setX(1.23).setY(3.45).output();
But not:
p0.output().setX(1.23);
As setX is not a const method (it doesn't declare that it won't modify the data inside the class instance to which it belongs).
You can call instead:
double x = p0.output().getX();
because getX is a const method.
Note: I am not saying you should use the methods in this way, but the point is to show what potentially you can do.
Setters are public metods thats allow you change private members of the class, they don't have return type so setX, setY should be void not Point:
void set(double x); // Declaration
void Point::setX( double x ) // Definition outside Point.h
{
xPoint = x;
}
Same with output should be void, rest is fine you can define it whatever you wish to display it, you can change it like this:
void Point::output() const
{
cout << "(" << xPoint << ", " << yPoint << ")";
}
setX() will probably change the value of the pointX member, and return a reference to the object being acted on.
So an implementation might be something like
Point &Point::setX(double xval)
{
if (IsValid(xval)) pointX = xval; // ignore invalid changes
return *this;
}
This can (assuming other member functions and operators are being used correctly) be used in things like this
#include <iostream>
// declaration of Point here
int main()
{
Point p;
std::cout << p.setX(25).setY(30).getX() << '\n';
}
While this example isn't particularly useful (it shows what is possible) the chaining of member function calls is useful in various circumstances. For example, this technique is actually the basis on which iostream insertion and extraction operators work, and allow multiple things to be inserted/extracted to/from a stream in a single statement.
The documentation of the setX and setY functions says
// mutator, returning reference to self
Your implementation does the mutation, but you've failed to complete the contract that this function is supposed to satisfy: it's supposed to return a reference to itself.
this is a pointer to the object you're invoking the method on, and so adding the line
return *this;
would complete the contract.
This is an aside, but it may help you understand why anyone would want to use such a 'strange' design.
You may be familiar with ordinary assignment being used in ways such as
a = b = 0;
if((result = some_function()) == 0) {
// Do something in the `result == 0` case
} else {
// Do something in the `result != 0` case
}
and other similar things. The first example sets both a and b to be 0. The second example stores the return value of the function call into the variable result, and then branches based on whether that value is 0 or not.
The way this works is that x = y is a binary operator that which has the side effect of copying the value of y into x, and then returns that value (technically a reference to x) so that it may be used in the surrounding expression.
So when you write a = b = 0, this is parsed as a = (b = 0), and has the effect of making b zero, and then evaluates to a = 0 which is then evaluated and makes a zero. Similarly for the branching example.
This is something people like to do when writing code (it's a completely separate topic whether or not this is good style), so when people design new types with operator= methods, they design them to support this usage, by making them return a reference to the object assigned to. e.g.
MyClass& MyClass::operator=(arg a)
{
// Copy the value of `a` into this object
return *this;
}
The other assignment operators, like operator+= also work this way.
Now, when you're used to this usage, it is a small step to extend it to other functions that sort of act like assignment, like setX and setY. This has the additional convenience of making it easy to chain modifications, as in point.setX(3).setY(7).