#include<iostream>
usingnamespace std;
class spl
{
public:
string myInt;
spl()
{
myInt="Hello this is my first text";
}
void change(string one)
{
myInt=one;
}
};
class alu
{
public:
int add(int *on,int *of)
{
*on += *of;
cout<<*on;
spl.change("This is second");
}
};
class mem
{
public:
spl obj1;
int oper1;
int oper2;
alu aluo;
mem()
{
oper1=4;
oper2=6;
}
void print()
{
cout<<oper1<<endl<<oper2<<endl;
}
void myFu()
{
aluo.add(&oper1,&oper2);
}
};
int main()
{
mem as;
as.myFu();
// system("pause");
}
In the code above there is an error on line 29. I want to execute it without making object of "spl" class. The object of "spl" is available in "mem" class. Neither I want to pass the parameter of "spl" object to the function add.
Please tell me how can I access the object "obj1" in the "alu" class which should be same of "mem" class, i.e. I dont want to make the new object in "alu" class. The object can't be access though the parameter either.
struct base
{
base() : v(35) {}
int foo( int a ) { return v += a ; }
int bar( int a ) { return v *= a ; }
int v ;
};
struct derived : base
{
int bar( int a ) // derived::bar hides base::bar
{
// call base class function
int x = foo(a) ; // base::foo(a)
// call base class function
int y = base::bar(a) ; // use scope resolution
return x + y ;
}
};
As things stand, you can't do this. Yes, the mem class owns an instance of the spl class. But the alu class doesn't have any knowledge of it. If you want an alu object to be able to call methods on an spl object, then you'll need to give it a pointer or reference to the spl object. It can't magically just know about that object.
Why can't you pass a pointer/reference as a parameter?
Oh, and how is this anything to do with inheritance? None of your classes inherits from any other class.
To writetonsharma:
You can't just make spl::change() a static method. It sets the value of a data member, so there needs to be an actual object of that type.
And using global variables is something to be avoided,.