ZoOl007
ZoOl007

Reputation: 417

c++ pass pointer between classes - access other class methods

I have this class instance

ControlPanel *cp = new ControlPanel();

Another class needs access to the methods in cp so I

Monitor *cpmon = new Monitor(cp);

The Monitor class header looks like

class Monitor {
public:
    Monitor(ControlPanel *_cp);
    ~Monitor();
private:
    ControlPanel *cp;
}

and the Monitor constructor looks like

#include "Monitor.h"

Monitor::Monitor(ControlPanel *_cp)
    {
    *cp = _cp; //doesn't work
    }

error is :

no match for ‘operator=’ (operand types are ‘ControlPanel’ and ‘ControlPanel*’)

now I printed the pointer addresses along the way and I can access the methods from within the constructor eg if I do _cp->SomeMethod it works but I don't know how I can code that the private *cp actually is the same address _cp points to so that I can access the cp intantiated at the very top from within Monitor's methods and not just from within its constructor - I read a lot - tried a zillion things, got a lot of different errors but I just can't make it work. Can someone clarify? How do I assign private *cp _cp's address please? thank you

Upvotes: 0

Views: 532

Answers (2)

blackpen
blackpen

Reputation: 2424

Either the ControlPanel must supply you with a assignment operator (a built-in assignment operator may do bitwise-copy and thus give you segfuault) OR you should start using just the pointers to ControlPanel (instead of copying the ControlPanel objects).

Both approaches have their advantages and disadvantages. If I have access to the source code of Control Panel, I would write a valid assignment operator (if it is required! Writing the special class functions in C++ must be done carefully in order to avoid surprises and painful troubleshotting later).

Upvotes: 0

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10887

The problem is you dereference the pointer and assign it to a pointer. To fix, simply change from

*cp = _cp;

to

cp = _cp;

Upvotes: 1

Related Questions