Operator overloading + with pointer array of class objects C++ - c++

I'm working on a small assignment for a class. I need to overload the '+' operator to add together two private member variables of a class object. The class objects are pointed to by an array of class pointers. I'm not quite sure where to start debugging, but my operator overload function causes the program to crash.
Here is main.cpp (ignore printObjects and freeObjects for now).
#include <iostream>
#include "Foo.h"
using namespace std;
void createObjects(Foo* fooArr[3], Foo* newFoo);
void printObjects(Foo* fooArr[3], Foo newFoo);
void freeObjects(Foo* fooArr[3], Foo newFoo);
int main()
{
Foo *fooArr[3] = { 0 };
Foo *newFoo = 0;
createObjects(&fooArr[3], newFoo);
Foo f1 = *(fooArr[1]) + *(fooArr[2]);
f1.outputX();
}
void createObjects(Foo* fooArr[3], Foo* newFoo)
{
for (int i = 0; i < 3; i++)
{
newFoo = new Foo(i+1);
fooArr[i] = newFoo;
}
}
Here is Foo.h:
using namespace std;
class Foo
{
private:
int x;
public:
Foo();
Foo(int);
void setX(int);
const int getX();
void outputX();
Foo operator+(const Foo&) const;
};
And finally here is foo.cpp:
#include <iostream>
using namespace std;
#include "Foo.h"
Foo::Foo(int x_)
{
x = x_;
}
void Foo::setX(int x_)
{
x = x_;
}
const int Foo::getX()
{
return x;
}
void Foo::outputX()
{
cout << x << endl;
}
Foo Foo::operator+(const Foo& f2) const
{
Foo f3(0);
f3.x = x + f2.x;
return f3.x;
}
The program crashes (segFault), right after calling the operator+ overload function. Now I know this means I am trying to access memory that the program doesn't actually have access to. However, I just don't know how to craft the operator overload statement to work with the function call:
Foo f1 = *(fooArr[1]) + *(fooArr[2]);
Any help would be much appreciated.
Thanks!

Related

Use an external function as a method of a class

I'm trying to make this code work:
#include <iostream>
using namespace std;
int f(int x) {
return x+1;
}
class A {
public:
int g(int y);
};
int A::g(int y) = f;
int main() {
A test;
cout << test.g(3) << endl;
return 0;
}
It does not compile because of the line int A::g(int y) = f;.
What is the correct way to achieve that an external function can be used as a method?
You can use a pointer to function as a member of class A. Now assign function f to g member of A.
int f(int x) {
return x+1;
}
class A {
public:
int (*g)(int);
};
int main(){
A test;
test.g = f;
cout << test.g(10); // prints 11
}
You can accomplish the same by making your function a callable objects by implementing () operator. so you can have that as member of the class, and then it can normally be used as function on the class objects.
#include <iostream>
struct do_something{
int operator()(int num){
return num;
}
};
class test{
int sum;
public:
do_something fun;
};
int main(){
test obj;
std::cout << obj.fun(10);
}

How can i pass structs across files by value

I’m able to produce a compilable piece of code that will pass structs to functions, however my code just falls apart when i’m trying to use ‘pass by value’.
I’ve looked at how to use the same formatted struct across multiple files, but i’m not sure if it’s any different when passing functions by value?
Note: this is written in the arduino IDE in C++
my code for passing by address follows:
passingStructs.ino
#include "a.h"
#include "b.h"
myStruct volatile structure1;
void setup() {
}
void loop() {
structure1.foo = 7;
structure1.bar = 11;
int lower = minusData(&structure1);
int higher = addData(&structure1);
}
a.h:
#include "b.h"
#ifndef __a_h
#define __a_h
//prototype functions
int addData(struct myStruct *structureC);
#endif //__a_h
a.cpp:
#include "a.h"
#include "b.h"
int addData(struct myStruct *structureC) {
int x = structureC->foo;
int y = structureC->bar;
return (x + y);
}
b.h:
#ifndef __b_h
#define __b_h
//Define structure
typedef struct myStruct {
int foo;
int bar;
};
//Prototype functions
int minusData(struct myStruct *structureC);
#endif //__b_h
b.cpp:
#include "b.h"
myStruct structureC;
int minusData(struct myStruct *structureC) {
int x = structureC->foo;
int y = structureC->bar;
return (x - y);
}
however if i use
int higher = addData(structure1);
in the .ino file and
int addData(struct myStruct structureC) {
int x = structureC.foo;
int y = structureC.bar;
return (x + y);
}
in the a.cpp file with the same prototype in the header file, the compiler rejects the code saying
no matching function for call to ‘myStruct::myStruct(volatile myStruct&)’
any ideas?
C++ will generate default constructors and a copy operator for structs and classes.
For your myStruct these implicit functions would be:
struct myStruct {
myStruct() {} // <-- implicit default constructor.
myStruct(const myStruct& other) // <-- implicit copy contructor
{
foo = other.foo;
bar = other.bar;
}
myStruct& operator = (const myStruct& other) // <-- implicit copy operator
{
foo = other.foo;
bar = other.bar;
return *this;
}
int foo;
int bar;
};
Note that the copy constructor and operator expect a const myStruct& parameter. The volatile keyword in your definition of myStruct volatile structure1; prevents parameter matching.
You'd have to explicitly declare a copy operator and/or constructor that accept a const volatile myStruct& to make your code compile.
volatile data needs special handling by the compiler's optimizer. That's why the volatile keyword is important here. You should really consider whether your data really needs this qualifier. On the Arduino, there is only one case where this keyword is needed, that is when the data is modified by an interrupt routine.
Alternatively, you can define functions that accept a volatile reference or pointer to data:
struct MyStruct // I suggest you use this syntax for declarting structures
{ // So you don't ghave to repeat the struct keyword everywhere.
myStruct(const myStruct& other)
{
foo = other.foo;
bar = other.bar;
}
myStruct(const volatile myStruct& other)
{
foo = other.foo;
bar = other.bar;
}
int foo, bar;
};
int addData(volatile const myStruct* structureC)
{
return structureC->foo + structureC->bar;
}
int addData(volatile const myStruct& structureC)
{
return structureC.foo + structureC.bar;
}
int addDataByCopy(myStruct structureC)
{
return structureC.foo + structureC.bar;
}
// ...
volatile myStruct my;
void loop()
{
my.foo = 1;
my.bar = 1;
int x = addData(my); // by const reference.
// or
int y = addData(&my); // by pointer.
// or
int z = addDataByCopy(my); // by copy
}

Using an interface class as member type in another class

I'm trying to design a piece of code that entails the use of an algorithm. The algorithm should be easily replaceable by someone else in the future. So in my LargeClass there has to be a way to invoke a specific algorithm.
I provided some example code below. My idea was to make an interface class IAlgorithm so that you have to provide an implementation yourself. I thought you could initialize it to which ever derived class you wanted in the constructor of the LargeClass. However the below code doesn't compile in VS2015 because IAlgorithm: cannot instantiate abstract class
My question: How should I design this in order to get the result I want?
Thanks in advance!
Algorithm.h
class IAlgorithm
{
protected:
virtual int Algorithm(int, int) = 0;
};
class algo1 : public IAlgorithm
{
public:
virtual int Algorithm(int, int);
};
class algo2 : public IAlgorithm
{
public:
virtual int Algorithm(int, int);
};
Algorithm.cpp
#include "Algorithm.h"
int algo1::Algorithm(const int a, const int b)
{
// Do something
}
int algo2::Algorithm(const int a, const int b)
{
// Do something
}
Source.cpp
#include "Algorithm.h"
class LargeClass
{
private:
IAlgorithm algo;
};
int main()
{
}
My first thoughts on this would be, why use such a primitive interface?
OK, we have a requirement that some process needs an algorithm sent into it. This algorithm must be polymorphic, it must take two ints and return an int.
All well and good. There is already a construct for this in the standard library. It's call a std::function. This is a wrapper around any function object with a compatible interface.
example:
#include <functional>
#include <iostream>
class LargeClass
{
public:
using algorithm_type = std::function<int(int,int)>;
LargeClass(algorithm_type algo)
: _algo(std::move(algo))
{}
int apply(int x, int y) {
return _algo(x,y);
}
private:
algorithm_type _algo;
};
int test(LargeClass&& lc) {
return lc.apply(5,5);
}
int divide(int x, int y) { return x / y; }
int main()
{
// use a lambda
std::cout << test(LargeClass{ [](auto x,auto y){ return x + y; } });
// use a function object
std::cout << test(LargeClass{ std::plus<>() } );
// use a free function
std::cout << test(LargeClass{ divide } );
// use a function object
struct foo_type {
int operator()(int x, int y) const {
return x * 2 + y;
}
} foo;
std::cout << test(LargeClass{ foo_type() } );
std::cout << test(LargeClass{ foo } );
}

Dereferencing pointer to functor inside a dereferenced class

I have a functor like this
struct foo
{
int a;
foo(a) : a(a) {}
int operator()(int b) { return a+b; }
};
And a class like this
class bar
{
public:
foo* my_ftor;
bar(foo* my_ftor) : my_ftor(my_ftor) {}
~bar() {}
};
Then suppose a pointer to this class, which contains a pointer to foo.
foo MyFoo(20);
bar MyBar(&MyFoo);
In a function I pass a reference to bar, and I want to run the functor. I got it working the following way:
void AnyFunction(bar* RefToBar)
{
int y;
y = RefToBar->my_ftor->operator()(25);
}
Is there any other "cleaner" way to dereference the functor? Something akin to
y = RefToBar->my_ftor(25);
won't work, sadly...
Any idea? Thank you
Use real references:
class bar {
public:
foo &my_ftor;
bar (foo &f) : my_ftor(f) {}
};
void AnyFunction (bar &reftobar) {
int y = reftobar.my_ftor(25);
}
And call like this
foo myFoo(20);
bar myBar (myFoo);
AnyFunction (myBar);
In the interest of completeness, here is another answer that is more of a modern approach.
class foo {
public:
foo (int i) : a(i) {}
int operator() (int x) const {
return x + a;
}
private:
int a;
};
template <typename F>
void AnyFunction (const F &func) {
int y = func(25);
}
So you can pass in a foo directly:
AnyFunction (foo (20));
Or another kind of function object, like a lambda:
AnyFunction([](int x) -> int {
return x + 20;
});
You could also extend bar to include the following function:
int run_foo (int x) const {
return my_ftor (x);
}
And bind it (#include <functional>):
AnyFunction (std::bind (&bar::run_foo, &myBar, std::placeholders::_1));
Use std::function they are designed to hold functor of any sort.
#include <functional>
#include <iostream>
struct foo
{
int _a;
foo(int a) : _a(a) {}
int operator()(int b) { return _a+b; }
};
class bar
{
public:
std::function<int (int)> _ftor;
bar(std::function<int (int)> my_ftor) : _ftor(my_ftor) {}
~bar() {}
};
void AnyFunction(bar& RefToBar)
{
int y = RefToBar._ftor(25);
std::cout << "Y: " << y << std::endl;
}
int AnotherFunction(int b)
{
return b + 11;
}
int main(int argc, char const *argv[])
{
foo MyFoo(20);
bar MyBar(MyFoo);
bar MyBar_2(AnotherFunction);
bar MyBar_3([](int b) { return b + 56; });
AnyFunction(MyBar);
AnyFunction(MyBar_2);
AnyFunction(MyBar_3);
return 0;
}
http://ideone.com/K3QRRV
y = (*RefToBar->my_ftor)(25);
(better use std::function and don't violate demeter)

Boost function and boost bind: Bind the return value?

This is related to this previous question: Using boost::bind with boost::function: retrieve binded variable type.
I can bind a function like this:
in .h:
class MyClass
{
void foo(int a);
void bar();
void execute(char* param);
int _myint;
}
in .cpp
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
myVector.push_back(boost::bind(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* param)
{
boost::function<void(void)> f = myVector[0];
_myint = atoi(param);
f();
}
But how can I bind a return value ? i.e.:
in .h:
class MyClass
{
double foo(int a);
void bar();
void execute(char* param);
int _myint;
double _mydouble;
}
in .cpp
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
//PROBLEM IS HERE: HOW DO I BIND "_mydouble"
myVector.push_back(boost::bind<double>(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* param)
{
double returnval;
boost::function<void(void)> f = myVector[0];
_myint = atoi(param);
//THIS DOES NOT WORK: cannot convert 'void' to 'double'
// returnval = f();
//MAYBE THIS WOULD IF I COULD BIND...:
// returnval = _mydouble;
}
If what you want is a nullary function that returns void but assigns a value to _myDouble with the result of foo() before doing so, then you cannot do this easily with just Boost.Bind. However, Boost has another library specifically catered to this sort of thing -- Boost.Phoenix:
#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <boost/phoenix/phoenix.hpp>
struct MyClass
{
MyClass() : _myVector(), _myInt(), _myDouble() { }
void setMyInt(int i);
void bar();
void execute();
private:
double foo(int const a) { return a * 2.; }
std::vector<boost::function<void()> > _myVector;
int _myInt;
double _myDouble;
};
void MyClass::setMyInt(int const i)
{
_myInt = i;
}
void MyClass::bar()
{
using boost::phoenix::bind;
_myVector.push_back(
bind(&MyClass::_myDouble, this) =
bind(&MyClass::foo, this, bind(&MyClass::_myInt, this))
);
}
void MyClass::execute()
{
if (_myVector.empty())
return;
_myVector.back()();
double const returnval = _myDouble;
std::cout << returnval << '\n';
}
int main()
{
MyClass mc;
mc.bar();
mc.setMyInt(21);
mc.execute(); // prints 42
mc.setMyInt(3);
mc.execute(); // prints 6 (using the same bound function!)
// i.e., bar has still only been called once and
// _myVector still contains only a single element;
// only mc._myInt was modified
}
problem 1: myVector needs to be a class member.
problem 2: myVector is interested in functions that return doubles and take no arguments, which would be boost::function<double()>
then, to bind _mydouble to the parameter of foo, call boost::bind(&MyClass::foo, this, MyClass::_mydouble) which should give you a compilation warning about casting a double to an int for when foo is called.
The closest you can come with Boost.Bind is providing the toreturn as a parameter.
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace std;
class Foo {
int myInt;
double myDouble;
public:
Foo() : myInt(3), myDouble(3.141592) { }
void SetToMyInt(double& param)
{
param = myInt;
}
void SetToMyDouble(double& param)
{
param = myDouble;
}
double Execute()
{
double toReturn = 2;
boost::function<void(double&)> f = boost::bind(&Foo::SetToMyDouble, this, _1);
f(toReturn);
return toReturn;
}
};
int main() {
Foo foo;
std::cout << foo.Execute() << std::endl;
return 0;
}