-
inheritance help...
hi, i was making a simple program that takes 2 floats in a base class then adds them through a dirived class, i complied and got no errors, but when i enter the numbers i get that wacky 2.1 -n 10 X 233.43454 some weird off the wall number...
anyways heres my code, i would appreciate a little guidence :)
Code:
#include <iostream>
using namespace std;
class Base
{
public:
void setNums(float, float);
float a;
float b;
};
void Base::setNums(float y, float u)
{
y = a;
u = b;
}
class Addy : public Base
{
public:
void add();
};
void Addy::add()
{
float sum = a + b;
cout<<"The sum is"<<sum<<endl;
}
int main()
{
float h = 0;
float g = 0;
Base a;
Addy b;
cout<<"Enter 2 floaters \n";
cin>>h>>g;
a.setNums(h,g);
b.add();
return 0;
}
-
Should
Code:
void Base::setNums(float y, float u)
{
y = a;
u = b;
}
be
Code:
void Base::setNums(float y, float u)
{
a = y;
b = u;
}
Could get some funny results otherwise ;)
-
nope.... damn this is annoying.... anyone know?
-
>anyone know?
b and a are unrelated, change
to
As it is b's data members are uninitialized and you're trying to work with them. This is undefined behavior, so anything could happen. You should also follow minesweeper's advice. :)
-
oh man noobie error! thanks alot! it worked :)
-
Code:
class Base
{
public:
void setNums(float, float);
float a;
float b;
};
should be
class Base
{
public:
void setNums(float, float);
protected:
float a;
float b;
};