#include <iostream>
using namespace std;

class fibonacci
{
private:
	int num;
public:
	long fibNum(int n);
	fibArr();
};
//============================
long fibonacci::fibNum(int n)
{
	n=num;
	if (n<0) { return 0; }
	if (n<2) { return n; }
	else { return fibNum(n-1) + fibNum(n-2); }
}
//============================
fibonacci::fibArr()
{
	int *Arr;
	Arr=new int[num];

	for (int i=0; i<num; i++)
	{ 
		Arr[i]=fibNum(i);
		cout<< Arr[i] << " ";
	}
}
//============================
//============================
int main()
{
	fibonacci fibo;
	fibo.fibNum(10);
	fibo.fibArr();

	return 0;
}

works, but doesn't return any values as supposed. What would need to be changed?

Recommended Answers

All 4 Replies

First, your code shouldn't compile because fibArr tries to use implicit int for the return value, which is illegal C++. Second, you don't even try to print the result of fibNum. Third, you should release the memory you allocate in fibArr. Finally, and this is the biggest error, you're not properly setting num, which is causing fibArr to seg fault. You're not even really using that data member, so you might as well just get rid of it:

#include <iostream>
using namespace std;

class fibonacci
{
public:
	long fibNum( int n );
	void fibArr( int n );
};
//============================
long fibonacci::fibNum(int n)
{
	if (n<0) { return 0; }
	if (n<2) { return n; }
	else { return fibNum(n-1) + fibNum(n-2); }
}
//============================
void fibonacci::fibArr(int n)
{
	int *Arr;
	Arr=new int[n];

	for (int i=0; i<n; i++)
	{ 
		Arr[i]=fibNum(i);
		cout<< Arr[i] << " ";
	}
}
//============================
int main()
{
	fibonacci fibo;

	cout<< fibo.fibNum ( 10 ) <<'\n';
	fibo.fibArr ( 10 );

	return 0;
}

I see, thanks for the corrections, or rather, for a remake :D
also, you wrote that my compiler shouldn't even compile the code in the first place, yet it did.
I'm using Ms Visual Studio 6, been advised by a couple of people. Should i switch to dev c++, or what complier is advised?
quick edit: is it better using your own made constructor/destructor or leave it be to the default one, because from the book i got it says the only big difference is that the code is clearer?

>I'm using Ms Visual Studio 6
Use something newer. Visual Studio 6 was released before C++ was standardized, so you'll have a lot of problems trying to learn correct C++. Visual C++ 2008 Express is a free download, so there's really no excuse to continue using a relatively ancient compiler.

>is it better using your own made constructor/destructor or leave it be to the default one
It depends on the data members of your class. But it's never wrong to explicitly define the default constructor.

i see, downloading ms visual studio '8 as i write.
yet again, thanks for the tips :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.