Simply add a getter method int get_x()
to Class1
#include <iostream>
#include <conio.h>
using namespace std;
class Class1{
private:
int x;
public:
Class1();
void Display();
int get_x();
};
int Class1::get_x()
{
return x;
}
class Class2{
private:
double z;
public:
Class2();
void Display();
Class2 Add(Class1);
};
Class1::Class1(){ x = 1; }
Class2::Class2(){ z = 5; }
void Class1::Display(){ cout<<x<<"\n"; }
void Class2::Display(){ cout<<z<<"\n"; }
Class2 Class2::Add(Class1 t){
Class2 y;
y.z = t.get_x() + z;
return y;
}
int main(){
Class1 ob1; // ob1 = 1 //
Class2 ob2,ob_x; // ob2 = 5 | ob_x = 5 //
ob_x = ob2.Add(ob1); // Add ob + ob1 and Assigned them to ob_x //
ob_x.Display();
cout<<endl;
getche();
return 0;
}
solved C++ Accessing Another Class Member [closed]