jbgs
jbgs

Reputation: 2885

Accessing member objects from another member object within the same class

Let's say I have the following C++ code:

class Circuit {
    public:
    Properties circuit_prop;
    Library tech_libray;
    InstanceList instances;
}

Properties, Library and InstanceList are classes defined in my code. And for example the class InstanceList has a member function called build. Is it possible to access the member object circuit_prop or tech_library without passing them as parameter to build? What would be the best approach to solve this problem?

Upvotes: 0

Views: 283

Answers (3)

Subhajit
Subhajit

Reputation: 320

circuit_prop or tech_library scope is within the class Circuit only, better make a method inside Circuit that has all the public access you need for separate classes.

Upvotes: 1

Benjamin Trent
Benjamin Trent

Reputation: 7566

Just because classes are associate members of the same class does not mean that they can freely access each others member objects. I would say making circuit_prop and tech_library members of InstanceList would be better than having them all members of the same class. This way you can get Circuit to access them freely from a get set set up or by making Circuit a friend class of InstanceList

Upvotes: 1

zennehoy
zennehoy

Reputation: 6846

No, this is not possible, because an InstanceList could just as well exist outside of Circuit.

If you have a method that needs to access various members, it should go into the class that has those members - in your case, Circuit.

Alternatively, InstanceList needs to know the Circuit it belongs to, in which case it can access the members via Circuit's public interface.

Upvotes: 2

Related Questions