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();
}
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 beint main() not void main()
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).
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.
#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.