Please help me solve this problem regarding inheritance.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
using namespace 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.
for line 29, you can make spl::change() as static and then can call it directly without any object.

about accessing, obj1. Either you can make it global or make it static and then use it from alu class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 ;
    }
};
To the OP:

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,.
Topic archived. No new replies allowed.