Can someone please tell whats wrong with this c++ code - c++

#include <iostream>
using namespace std;
class Complex{
private:
int a,b;
public:
void set_data(int x,int y){
a=x,b=y;
}
void show_data(){
cout<<a<<" "<<b<<endl;
}
};
Complex add(Complex c, Complex d){
Complex temp;
int a = c.a+c.b;
int b = d.a+d.b;
temp.set_data(a,b);
return temp;
};
int main()
{
Complex c1,c2,c3;
c1.set_data(2,3);
c2.set_data(4,5);
c3 = add(c1,c2);
c3.show_data();
return 0;
}
want to know why add function is not wrking where as if i write c1.add(c2) and define function inside class then it works completely fine

"a" and "b" are declared as private. You cannot access it from outside the class. You need to make it public or provide getters or move it to inside the class.

As others pointed out, the member variables "a" and "b" are private and therefore can't be accessed from outside the class. Also, mind that your "add" function may not be mathematically correct. If you mean to add two complex numbers you probably want to write:
int a = c.a + d.a;
int b = c.b + d.b;
where I assume "a" is the real part and "b" the imaginary part

As the class variables "a" and "b" are private, you need to write getter functions for them. Sample code as follows:
#include <iostream>
using namespace std;
class Complex{
private:
int a,b;
public:
void set_data(int x,int y){
a=x,b=y;
}
void show_data(){
cout<<a<<" "<<b<<endl;
}
int getA(){
return a;
}
int getB(){
return b;
}
};
Complex add(Complex c, Complex d){
Complex temp;
int a = c.getA()+c.getB();
int b = d.getA()+d.getB();
temp.set_data(a,b);
return temp;
}
int main()
{
Complex c1,c2,c3;
c1.set_data(2,3);
c2.set_data(4,5);
c3 = add(c1,c2);
c3.show_data();
return 0;
}
Or make the variables public to directly access from anywhere. Sample as follows:
#include <iostream>
using namespace std;
class Complex{
public:
int a,b;
public:
void set_data(int x,int y){
a=x,b=y;
}
void show_data(){
cout<<a<<" "<<b<<endl;
}
};
Complex add(Complex c, Complex d){
Complex temp;
int a = c.a+c.b;
int b = d.a+d.b;
temp.set_data(a,b);
return temp;
};
int main()
{
Complex c1,c2,c3;
c1.set_data(2,3);
c2.set_data(4,5);
c3 = add(c1,c2);
c3.show_data();
return 0;
}

So, there's a lot to discuss here and it's a bit tough because it's hard to know what you're allowed to use. I've tried to remove that notion from my courses, at least.
Your class lacks any constructors. Relying solely on a setter is poor practice. Constructors are the correct way to initialize an object, and they are more efficient than a default initialization + setter.
You overuse the comma operator for no real gains. It just muddies readability.
Your add() function attempted to access private data, that's a big no-no. It would defeat the purpose if any free function could access private data as it pleased. The reason implementing the function inside the class worked fine is because as a class member function, it has access to the private section. Either make it a class member funtion OR add getters for your data.
The following sample adds constructors, replaces functions with operator overloads where they fit, and made a few other "better" practice changes. It also includes functionality that is available in C++17.
When I help with homework questions like this, my preference is to use a couple things that are likely to have not been discussed yet; it helps prevent copy/paste dishonesty. But I believe it still helps in seeing the logic play out.
#include <iostream>
#include <string>
#include <tuple>
class Complex {
public:
Complex() = default;
Complex(int r, int i) : m_real(r), m_imaginary(i) {}
auto get_data() const { return std::make_tuple(m_real, m_imaginary); }
void set_data(int x, int y) {
m_real = x;
m_imaginary = y;
}
private:
int m_real = 0;
int m_imaginary = 0;
};
Complex operator+(const Complex& lhs, const Complex& rhs) {
auto [leftReal, leftImaginary] = lhs.get_data(); // C++17 feature
auto [rightReal, rightImaginary] = rhs.get_data();
return Complex(leftReal + rightReal, leftImaginary + rightImaginary);
}
// No newline printed here because no other Standard type does that
std::ostream& operator<<(std::ostream& sout, const Complex& obj) {
auto [real, imaginary] = obj.get_data();
// If you care about setw() interacting with your output, this intermediate
// step matters
std::string val =
std::to_string(real) + " + " + std::to_string(imaginary) + "i";
return sout << val;
}
int main() {
Complex c1(2, 3);
Complex c2(4, 5);
Complex c3 = c1 + c2;
std::cout << c3 << '\n';
return 0;
}

Related

C++ "Incomplete type is not allowed" trying to create array of functions inside a class

How do I get the below code example, that compiles and works just fine to work inside a class?
Below code works just fine
#include <iostream>
using namespace std;
typedef int (*IntFunctionWithOneParameter) (int a);
int function(int a){ return a; }
int functionTimesTwo(int a){ return a*2; }
int functionDivideByTwo(int a){ return a/2; }
void main()
{
IntFunctionWithOneParameter functions[] =
{
function,
functionTimesTwo,
functionDivideByTwo
};
for(int i = 0; i < 3; ++i)
{
cout << functions[i](8) << endl;
}
}
So the above code works fine, but I want to move it inside a class in a separate file, similar to the below NON-WORKING IDEA, where I get "incomplete type is not allowed" error at "functions[] =";
class myClass {
private:
typedef int (*IntFunctionWithOneParameter) (int a);
int function(int a){ return a; }
int functionTimesTwo(int a){ return a*2; }
int functionDivideByTwo(int a){ return a/2; }
IntFunctionWithOneParameter functions[] =
{
function,
functionTimesTwo,
functionDivideByTwo
};
};
So my question is how can I get it to work inside my class, where it is the ONLY place the functions are needed, meaning I do need to access the functions in main() or other places!
EDIT
Here is why I need an "array of functions". To save time spent on "if's" or more exactly "switches" as I am making a software (vst) synthesizer, and the less time spent in the processing, the more notes (polyphonic) the user can play at any given time. And multiply the 44100 times per second the function is run, with 8 tone generators, which each can have up to 16 unison voices, so actually the function needed, may be called up to 5,644,800 times per second, per note played! The exact function needed inside this main loop is known BEFORE entering loop, and ONLY changes when the user adjust a knob, so I do want to avoid ifs and switches. Now had it only been one function that occasionally changes, i could just duplicate main loop with variations for each function possible, HOWEVER the main audio processing loop, has several areas, each with a variety of ever growing functions possible, each which ONLY changes when user changes various knobs. So although I could, I am not going to make 5 * 20 * 23 (and growing) different versions of a main loop, to avoid if's and switches.
There's a bunch of things wrong with the code that you posted:
No semicolon after class definition.
Class instead of class
No fixed size set for the functions member, which is not allowed. You need to explicitly set the size of the array.
Member function pointers are not the same as "regular" function pointers. Member function pointers have an implicit this as first argument, since they need an object to be invoked on. So myFunction is not of type myArrayOfFunctions. If you make myFunction and myFunction2 static, then they can be stored as regular function pointers. Is this an option?
The name myArrayOfFunctions is very confusing, since it's not an array at all.
All but the last of these will cause your code not to compile.
This example may be what you've needed.
Note: I've changed typedef statement to using and changed function's signatures to take in plain int for testing convinience sake.
class myClass {
public:
using myArrayOfFunctions = float(myClass::*)(int a, int b, float c);
float myFunction1 (int a, int b, float c)
{
return a * b * c;
}
float myFunction2 (int a, int b, float c)
{
return a + b + c;
}
myArrayOfFunctions functions[2];
myClass()
{
functions[0] = &myClass::myFunction1;
functions[1] = &myClass::myFunction2;
};
void Invoke()
{
(this->*functions[0])(1, 2, 3);
(this->*functions[1])(3, 2, 1);
}
};
int main()
{
myClass a;
a.Invoke();
(a.*(a.functions[0]))(4, 5, 6);
return 0;
}
As you see, I'm getting the pointer to the class function but to call it I need to call it with an actual object (this in invoke() function and a object in main()).
You can write this:
class myClass
{
public:
typedef float (*myArrayOfStaticFunctions) (int& a, int& b, float& c);
typedef float (myClass::*myArrayOfFunctions) (int& a, int& b, float& c);
static float myFunction1 (int& a, int& b, float& c){cout<<"myFunction1"<<endl; return 0;}
static float myFunction2 (int& a, int& b, float& c){ cout<<"myFunction2"<<endl; return 0;}
float myFunction3 (int& a, int& b, float& c){ cout<<"myFunction3"<<endl; return 0;}
float myFunction4 (int& a, int& b, float& c){ cout<<"myFunction4"<<endl; return 0;}
myArrayOfStaticFunctions StaticArrayfunctions[2];
myArrayOfFunctions Arrayfunctions[2];
myClass (){
StaticArrayfunctions [0] =myFunction1;
StaticArrayfunctions [1] =myFunction2;
Arrayfunctions [0] = &myClass::myFunction3;
Arrayfunctions [1] = &myClass::myFunction4;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
myClass m;
int a =0, b=0; float c;
m.StaticArrayfunctions[0] (a,b,c);
m.StaticArrayfunctions[1] (a,b,c);
myClass::myArrayOfFunctions func3 = m.Arrayfunctions[0];
myClass::myArrayOfFunctions func4 = m.Arrayfunctions[1];
(m.*func3)(a,b,c);
(m.*func4)(a,b,c);
return 0;
}

C++ Using member functions from a similar virtual public class

Suppose I have a bunch of inherited classes like this:
...and they all serve the purpose of making all sorts of polynomials. Class X is mainly a variable tank, classes A, B, etc are all virtual public X and each creates ont type of polynomial, class Y makes the calls. Besides A and B, any other class can be added.
Now, everything works but for a newly added "virtual public" class I need to reuse some member function(s) from other classes, here from A inside class B. I tried to make the simplest example:
#include <iostream>
#include <cmath>
#include <functional>
// variable tank
class X
{
protected:
// general variables
double *m_c;
int m_n;
double m_w;
// funcX related
double m_r;
int m_i {0};
public:
~X() = default;
/* Simple bracketed root-finding. This is called from more than
* one "virtual public" classes.
*/
const double funcX(const double &x, const double &y, \
std::function<const double(const double&, const int&)> fp, \
const int &k)
{
double a {x}, b {y}, fmid;
while (m_i<100)
{
m_r = 0.5*(a + b);
fmid = fp(m_r, k);
if (fabs(b-a) <= 1e-3)
break;
if (fmid < 0)
b = m_r;
else
a = m_r;
++m_i;
}
return m_r;
}
};
// one of the many classes that generate polynomials
class A: virtual public X
{
public:
void funcA(const int &n)
{
// set order
m_n = n;
// calculate X::m_c[i]
m_c = new double[m_n+1];
for (short i=0; i<=m_n>>1; ++i)
{
int sgn {i%2 ? -1 : 1};
m_c[i<<1] = sgn/((i + 1.0)*(i + 1.0));
}
// The polynomial is zero somewhere, use funcX() to find where.
m_w = funcX(5.0, 0.0, \
[this](const double &x, const int &n) \
{ return calcA(x, n); }, \
m_n);
}
// calculates the value of the polynomial of order n, at x
const double calcA(const double &x, const int &n) const
{
double out {static_cast<double>(m_c[0])};
for (short i=1; i<=n; ++i)
out = m_c[i] + x*out;
return out;
}
};
class B: virtual public X
{
private:
A m_a; // otherwise the lambda function does not "catch" it
public:
void funcB(const int &n)
{
// same as in A
m_n = n;
// same as in A, calculate coefficients
m_c = new double[m_n+1];
for (short i=0; i<=m_n; ++i)
{
int sgn {i%2 ? -1 : 1};
m_c[i] = sgn/((i + 1)<<1);
}
/* Here I need A::calcA(). Instead of duplicating the code,
* I want to call it through X::funcX(). The code compiles,
* but it crashes.
*/
m_w = funcX(0.5, 1.0, \
[this](const double &x, const int &n) \
{ return m_a.calcA(x, n); }, \
m_n);
}
const double getW() const { return m_w; }
};
class Y: public A, public B
{
public:
Y(const int &n, const int &i)
{
// call one of the "virtual public" classes through i
switch (i)
{
case 1: funcA(n); break;
case 2: funcB(n); break;
}
}
void printC() { for (short i=0; i<=m_n; ++i) std::cout << m_c[i] << '\n'; }
void printW() { std::cout << m_w << '\n'; }
void printA(const double &x, const double &n) { std::cout << A::calcA(x, n) << '\n'; }
};
int main(int argc, char *argv[])
{
int N {6};
Y *y;
for (short i=1; i<=2; ++i)
{
y = new Y(N, i);
y->printC();
y->printW();
y->printA(1.2, N);
}
return 0;
}
class X:
X::funcX() is a simple root-finding algorithm which gets called in more than one virtual public classes (A, B, etc). m_c, m_n, m_w are shared variables.
classes A and B:
their main function is funcA() (and funcB(), and so on) and it creates the polynomial (in the body, there's a for loop), based on the calculated order, X::m_n. Evaluating the polynomial is A::calcA(). This needs to be either called by class B, too, or redefined. I'd rather avoid the latter because of the code bloating. It also doesn't look very "professional" for my fairly beginner level...
class Y
This calls any of the virtual public classes based on argument i (the switch/case).
The code compiles, but crashes. It prints the case for. This example points to A::funcA() as the culprit, but in the original program I can see that the coeficients, m_c[i], are not even initialized with dynamic memory, as in trying to print out m_c[0] crashes. I tried moving the new double[] insode the function in A, but that doesn't work.
I don't know how to make it. Does this make sense, is it possible? If yes, how?
Edit: Forgot to add that I can't just move calcA() from A to the top, in X, because each polynomial is evaluated differently, as in there are shortcuts, changes, in every one that makes it possible to have different, optimized evaluations for each polynomial. I could make X::calcA() a universal one, but there will be a performance penalty, which I'd rather not pay.
It seems that your problem is induced by problems with design. When you need to use methods from other class that may mean:
The is a problem with "single responsibility" principle. Class does too much. For example numerical equation solving algorithms are self-sufficient entities and shouldn't be part of polynomial. They can work with any polynomial.
There is a problem with inheritance tree. For example a common ancestor should be created and that common methods should be in it. Note, that if you can't find short and understandable name for that ancestor, then this is not the solution.
Inheritance is not used properly. For example I can't see virtual methods in your code which is strange.
Let's get closer to your example. You are using virtual multiple inheritance which is considered to be very heavy pattern and usually should not be used. Moreover, there are no virtual methods in your code, so you actually do not use inheritance at all. You either must drop inheritance, or think of common methods which make sense for all your classes. For functions this seems to be an ability to calculate function value in specified point. Then move all code, that is not describing polynomials or functions out of the classes. Move out numerical solvers. This will allow to reuse them for all your classes, that support needed interface. Get rid of Y class at all. It seems, that it is needed to emulate virtual methods with switches and enums. You don't need it, rename funcA and funcB just to func if they are semantically the same and do the same thing for different types of polynomials.

How to chain multiple operator[]

I am trying to create a class that use the operator [] like
MyClass[x][y]
and it should return a value based on what I call in the function that is defined within the class. What I have so far is:
MyClass.h
class MyClass{
public:
// return one value of the matrix
friend double operator[][] (const int x, const int y);
}
I don't even think my syntax for this is right, and how can I write this function in MyClass.cpp to define what value it should return?
Like is it:
MyClass::friend double operator[][] (const int x, const int y)
{
// insert code here
}
Tried it but it keeps saying errors. I believe it is a mess up there...
Many thanks,
Overloading operator() is definitely the cleanest approach.
However, remember that this is C++, and you can bend the syntax to your will :)
In particular, if you insist on wanting to use myclass[][], you can do so by declaring an "intermediate class", here's an example:
Run It Online
#include <iostream>
using std::cout;
using std::endl;
class MyClass {
public:
using IndexType = int;
using ReturnType = double;
// intermediate structure
struct YClass {
MyClass& myclass;
IndexType x;
YClass (MyClass& c, IndexType x_) : myclass(c), x(x_) {}
ReturnType operator[](IndexType y_) { return myclass.compute(x, y_); }
};
// return an intermediate structure on which you can use opearator[]
YClass operator[](IndexType x) { return {*this, x}; }
// actual computation, called by the last "intremediate" class
ReturnType compute(IndexType x, IndexType y) {
return x * y;
}
};
int main()
{
MyClass myclass;
cout << myclass[2][3] << endl; // same as: cout << myclass.compute(2, 3) << endl;
}
You need to return a proxy object for the row. This is a very simplified example just to get you going. I have not tried compiling it.
class Matrix {
int data[4][4];
class Row {
Matrix* matrix;
int row;
int operator[](int index){
return matrix->data[row][index]; // Probably you want to check the index is in range here.
}
}
Row operator[](int row){
Row which_row;
which_row.matrix = this;
which_row.row = row; // beware that if the user passes the row around it might point to invalid memory if Matrix is deleted.
return which_row;
}
}
You could also just return the row directly from operator[] and leave the second [] to be a direct array access. IMHO it is nice with the proxy object as it can do some checking on the index and possibly have other nice member functions.
There is no operator[][]. But you can declare operator()(int, int) instead.
class Foo {
public:
double operator()(int a, int b) {
//...
}
};
If you're trying to create 4x4 Matrix class, the way I did it and the way its done in the D3DX library is to have a member variable in the class:
class Matrix
{
public:
// publicly accessible member 4x4 array
float m[4][4];
// also accessible via () operator. E.G. float value = mtx(3,2);
float operator()(int column, int row);
}

how to return multiple values from get function in c++ [duplicate]

This question already has answers here:
Returning multiple values from a C++ function
(23 answers)
Closed 8 years ago.
I am basically passing two parameters in the private class and I am trying to access these two parameters in my main function. Since I made those two parameters private, I am using get and set functions to access these parameters, but I am not able to return two values from the get function. Please help me. The last post that asked kind of same question, but this time it has been asked for object oriented concept.
class FirstClass{
public:
void setName(int x,int y){
a = x;
b = y;
}
int getName(){
return a,b;
}
private:
int a,b;
};
Either use references:
int getName(int &a1, int &b1) {
a1 = a;
b1 = b;
}
or use two functions:
int getA() {
return a;
}
int getB() {
return b;
}
You can return a single value or take parameters as value-result arguments ( pointers or references) or return structure with parameters packed. Most probably you will need to access just a or just b separately after all, so why not to just create two accessors
int getNameA(){
return a;
}
int getNameB(){
return b;
}
accessors/mutators or getters/setters are intended to get/set only one value. Your code should be like this:
class FirstClass{
public:
FirstClass(int x,int y){ //constructor, initialize the values
a = x;
b = y;
}
int getA(){
return a;
}
int getB(){
return b;
}
int setA(const int newVal){ //using const is a good practice
a=newVal;
}
int setB(const int newVal){ //using const is a good practice
b= newVal;
}
// you can use reference/pointer to *obtain* multiple values, although it is rarely used and seems inappropriate in your code
void getBoth(int& aRef, int& bRef){
aRef = a;
bRef = b;
}
private:
int a,b;
};

passing a class method as opposed to a function in std::sort

Within a class, I am trying to sort a vector, by passing a method of the same class. But it gives errors at the time of compilation. Can anyone tell what the problem is? Thank you!
it gives the following error:
argument of type bool (Sorter::)(D&, D&)' does not matchbool (Sorter::*)(D&, D&)'
I have also tried using sortBynumber(D const& d1, D const& d2)
#include<vector>
#include<stdio.h>
#include<iostream>
#include<algorithm>
class D {
public:
int getNumber();
D(int val);
~D(){};
private:
int num;
};
D::D(int val){
num = val;
};
int D::getNumber(){
return num;
};
class Sorter {
public:
void doSorting();
bool sortByNumber(D& d1, D& d2);
std::vector<D> vec_D;
Sorter();
~Sorter(){};
private:
int num;
};
Sorter::Sorter(){
int i;
for ( i = 0; i < 10; i++){
vec_D.push_back(D(i));
}
};
bool Sorter::sortByNumber(D& d1, D& d2){
return d1.getNumber() < d2.getNumber();
};
void Sorter::doSorting(){
std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber);
};
int main(){
Sorter s;
s.doSorting();
std::cout << "\nPress RETURN to continue...";
std::cin.get();
return 0;
}
Make Sorter::sortByNumber static. Since it doesn't reference any object members, you won't need to change anything else.
class Sorter {
public:
static bool sortByNumber(const D& d1, const D& d2);
...
};
// Note out-of-class definition does not repeat static
bool Sorter::sortByNumber(const D& d1, const D& d2)
{
...
}
You should also use const references as sortByNumber should not be modifying the objects.
Unless you have a really good reason to do otherwise, just define operator< for the type of items you're sorting, and be done with it:
class D {
int val;
public:
D(int init) : val(init) {}
bool operator<(D const &other) { return val < other.val; }
};
class sorter {
std::vector<D> vec_D;
public:
void doSorting() { std::sort(vec_d.begin(), vec_D.end()); }
};
The way you're writing your sorter class depends on knowing a lot about the internals of the D class, to the point that they're practically a single class (e.g., it looks like neither can do much of anything without the other).
At a guess, your sorter may be a somewhat stripped-down version of your real code. The SortByNumber makes it sound like the original code might support a number of different kinds of keys, something like:
class D {
std::string name;
int height;
int weight;
// ...
};
and you'd want to be able to sort D objects by name, height, or weight. In a case like that, the comparisons are really still related to the D class, so I'd probably put them into a common namespace:
namespace D {
class D {
std::string name;
int height;
int weight;
public:
friend class byWeight;
friend class byHeight;
friend class byName;
// ...
};
struct byWeight {
bool operator()(D const &a, D const &b) {
return a.weight < b.weight;
}
};
struct byHeight {
bool operator()(D const &a, D const &b) {
return a.height < b.height;
}
};
struct byName {
bool operator()(D const &a, D const &b) {
return a.name < b.name;
}
};
}
Then sorting would look something like:
std::vector<D::D> vec_D;
// sort by height:
std::sort(vec_D.begin(), vec_D.end(), D::byHeight());
// sort by weight:
std::sort(vec_D.begin(), vec_D.end(), D::byWeight());
// sort by name:
std::sort(vec_D.begin(), vec_D.end(), D::byName());
Note that this does not use free functions. For this kind of purpose, a functor is generally preferable. I've also used a namespace to show the association between the object being sorted and the different ways of sorting it. You could make them nested classes instead, but I'd generally prefer the common namespace (keep coupling as loose as reasonable).
In any case, I would not give access to the raw data (even read-only access) via the object's public interface if it could be avoided (and in this case, it can be).
I see no reason for sortByNumber() to be a member function. When it's a member function it gains access to things it doesn't need (and therefore shouldn't have access to). Either extract the method and refactor it into a function object:
struct sortByNumber {
bool operator()(const D& d1, const D& d2) const {
return d1.getNumber() < d2.getNumber();
}
};
or make it a free function. Given the choice you should prefer a function object, because that makes it possible for the compiler to inline the code if it so chooses. Then, you can sort like so:
std::sort(vec_D.begin(), vec_D.end(), sortByNumber());
That said, you can get the code to compile as is like so, with boost::bind():
std::sort(vec_D.begin(), vec_D.end(),
boost::bind(&Sorter::sortByNumber, this, _1, _2));
You will need the boost libraries for that to work, and you will need to #include <boost/bind.hpp>.
I don't see any reason to make sortByNumber as a member function of class Sorter. You can do the sorting much more easily avoiding all the ugly bind code if you make it a free function. Also, you should use const wherever it is applicable in the code. Following is the example of doing it using free function:
First change the int getNumber() to const function as int getNumber() const;
Then write your free function sortByNumber again taking parameters by const reference.
bool sortByNumber(const D& d1, const D& d2);
You can call sort as :
std::sort(vec_D.begin(), vec_D.end(), sortByNumber);