Source Code
#include <iostream>
using namespace std;
class A
{
private:
long int a;
public:
long int b,x;
void set_a(){
cout<<"Enter variable A's value (integer) \nAnswer: ";
cin>>a;
x=a;
}
void display_a(){
cout<<"\n value for Variable A: "<<x<<endl;
}
void getdata(){
cout<<"Enter variable B's value (integer) \nAnswer: ";
cin>>b;
}
};
class B:public A
{
private:
long int prod;
public:
void prod(){
prod = x*b;
}
void display(){
cout<<"Displaying product of variables A and B \nProduct: "<<prod<<endl;
}
};
int main()
{
A obj;
B obj2;
obj.set_a();
obj.display_a();
obj2.display();
}
Complier Error Message
37 | }
| ^
main.cpp:31:16: note: previous declaration ‘long int B::prod’
31 | long int prod;
| ^~~~
I have just started learning Inheritance functions from Object Oriented programming so I am quite the novice. I believe the program lies within the Inheritance function sub class but I am not too sure.
Also, I am pretty sure there is a method to checking the solution to error messages from the compiler but I don't know what it is or where to look, so some assistance would be helpful
CodePudding user response:
There are 2 problems with your code described below.
Problem 1
You have a method prod
with the same name as the data member prod
in class B
.
To solve this change, you can either change the name of the method or the data member so that they're not the same as shown below.
Problem 2
The code has undefined behavior because you're using the value of the uninitialized data member b
.
To solve this make sure that b
is initialized(or assigned) before using its value as shown below. Similarly, prod
is uninitialized.
Additionally, you were creating a separate object obj
and calling the member functions on that object. That obj
is different from the subobject A
inside B
object obj2
. This has been fixed and highlighted using comments in the below program so that you can see what changes have been made.
class A
{
private:
long int a;
public:
long int b,x;
void set_a(){
std::cout<<"Enter variable A's value (integer) \nAnswer: ";
std::cin>>a;
x=a;
}
void display_a(){
std::cout<<"\n value for Variable A: "<<x<<std::endl;
}
void getdata(){
std::cout<<"Enter variable B's value (integer) \nAnswer: ";
std::cin>>b;
}
};
class B:public A
{
private:
long int prod;
public:
//-------vvvvvvv------------->name changed to product so that it is different from prod data member
void product(){
//call these methods here inside product instead of calling them outside on a separater `A` object
set_a();
getdata();
display_a();
prod = x*b;
}
void display(){
std::cout<<"Displaying product of variables A and B \nProduct: "<<prod<<std::endl;
}
};
int main()
{
//no need to create a separate `A` object
B obj2;
obj2.product();
obj2.display();
}
In the above program the call to member functions set_a
, getdata
and dispaly_a
is made from inside the member function product
instead of calling them on a separate A
object.