Thread: inheritance help...

  1. #1
    tetra
    Guest

    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;
    }

  2. #2
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798
    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

  3. #3
    tetra
    Guest
    nope.... damn this is annoying.... anyone know?

  4. #4
    Open to suggestions Brighteyes's Avatar
    Join Date
    Mar 2003
    Posts
    204
    >anyone know?
    b and a are unrelated, change
    Code:
    a.setNums(h,g);
    to
    Code:
    b.setNums(h,g);
    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.
    p.s. What the alphabet would look like without q and r.

  5. #5
    tetra
    Guest
    oh man noobie error! thanks alot! it worked

  6. #6
    Registered User devil@work's Avatar
    Join Date
    Mar 2003
    Posts
    33
    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;
    };

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  3. inheritance and performance
    By kuhnmi in forum C++ Programming
    Replies: 5
    Last Post: 08-04-2004, 12:46 PM
  4. Inheritance and Polymorphism
    By bench386 in forum C++ Programming
    Replies: 2
    Last Post: 03-18-2004, 10:19 PM
  5. Inheritance vs Composition
    By Panopticon in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2003, 04:41 AM