Suzi
February 22nd, 2008, 03:36 AM
Maybe you can help me with a small question. It is kind of hard to explain, but I made a little code example that I hope explains my thoughts.
I'm thinking of the code that calls the print function with the second element in the array: print(a+1);
What I think I'm doing is that I sends an pointer to a[1] into the function print.
It seems to works as I intended but is it safe to do it this way? (Nevermind that it is not the simplest or prefered way to do this.) Also, if the class Something is an subclass to another class, does it change anything?
#include <iostream>
using namespace std;
class Something
{
public:
Something(int in = 0){ n = in; };
void setData(int in) { n = in; };
int getData() { return n; };
protected:
int n;
};
void print(Something *in)
{
cout << in->getData() << endl;
}
int main()
{
Something a[5];
a[0].setData(1);
a[1].setData(2);
a[2].setData(3);
print(a+1);
char wait;
cin.get(wait);
}
I'm thinking of the code that calls the print function with the second element in the array: print(a+1);
What I think I'm doing is that I sends an pointer to a[1] into the function print.
It seems to works as I intended but is it safe to do it this way? (Nevermind that it is not the simplest or prefered way to do this.) Also, if the class Something is an subclass to another class, does it change anything?
#include <iostream>
using namespace std;
class Something
{
public:
Something(int in = 0){ n = in; };
void setData(int in) { n = in; };
int getData() { return n; };
protected:
int n;
};
void print(Something *in)
{
cout << in->getData() << endl;
}
int main()
{
Something a[5];
a[0].setData(1);
a[1].setData(2);
a[2].setData(3);
print(a+1);
char wait;
cin.get(wait);
}