Random values being displayed in simple inheritance

This is the program to perform simple inheritance but while performing add function, the output is not as it is supposed to be.
I am a beginner so please keep it simple
Thank you

#include<iostream.h>
#include<conio.h>
class add
{
int x,y;
public:
add(){}
add(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<x<<"+"<<y<<"="<<x+y<<endl;
}
};
class mul:public add
{
int m,n;
public:
mul(int a,int b)
{
m=a;
n=b;
}
void display1()
{cout<<m<<"*"<<n<<"="<<m*n<<endl;
}
};
void main()
{
clrscr();
add a1();
mul m1(2,3);
m1.display();
m1.display1();
getch();
}


Output :
1230+1206=2436
2*3=6

Please, format your code with the proper Code tags. it is very hard to read your code as it is now.

Anyway, You are getting odd values because you are trying to output UNINITIALIZED VARIABLES with your display function

my advice:
* i assume you are using c++, so the .h is not needed in the <iostream> header
* Read about Private Class members
* Your main should be int main() not void main()


Last edited on
Hi,
i think this problem exist, because function display(), is using 'x' and 'y', but in class "mul", you don't have 'x' OR 'y', so, it will continue operation with garbage values.
to get correct answer, overload display() function, with display(int _x, int _y) and then, when you want to use display in "mul" objects, use display(int _x, int _y).
closed account (SECMoG1T)
This is the reason you got those values :

class mul publicly inherits all data members from class add , so mul would have the following data members {x,y,n,m} , the problem result from failure to initialize the inherited members of add in the derived class hence they would contain undefined values.

This should have been the correct way to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 #include<iostream>          ///standard c++ have no header iostream.h
                                          ///#include<conio.h> never use this again

class add
{
  private: 
      int x,y;
 public:
    add(){}
    add(int a,int b):x(a),y(b){} ///prefer list initialization to copy initialization x=a,y=b
    void display()
   {
     std::cout<<x<<"+"<<y<<"="<<x+y<<std::endl;
   }
};

class mul:public add
{
  private:
      int m,n;
  public:
     mul():add(),m(0),n(0){}///default constructor
     mul(int _x,int _y,int a,int b): add(_x,_y),m(a),n(b){}
     ///or if you intended all members to have the same values 
     ///mul(int a,int b):add(a,b),m(a),n(b){}would take care of that
     void display1()
    {
        std::cout<<m<<"*"<<n<<"="<<m*n<<std::endl;
    }
};

int main()///standard c++ requires main to return an int. 


that should work.
Last edited on
Topic archived. No new replies allowed.