Sharing variables between objects of different classes (C++) - c++

I feel like I should already know how to do this but I'm not really sure of the best way to do it.
I have class A with a private class B object and class C object in it, and in the class C object, I need to access members of the class B object and the parent class A object, is there an easy way to do that?

In class C, you may have members that are pointers to Class B and class A objects. But anyway there is no straight way to access private variables of an object from outside.

You probably have to 'inject' these dependencies by passing a reference for class A (through which you can access class B anyway) to class C, either via the constructor of class C or some method that you define.
In class C you can define the type of the reference (ie a pointer) and then assign it the value from the input of the constructor or the method (depending on what option you choose).
EDIT: #Nipun is correct, if object B is private then u can't access it from outside of itself anyway.

This isn't really the place for me to say this, but if I find myself in a situation like this it generally means that I have designed my classes messily and they need adjusting or a complete redesign...

Related

Is there a way to bring all definitions in a C++ struct/class into scope without deriving from it?

Musing on a Sunday...
Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class.
Is there a way to achieve the former without the latter? I'm asking in the interest of concise notation.
Obviously, when the base class doesn't have any data members, I get what I want. There are quite a few empty classes or class templates in the standard library defined to do just that - inject names summarily into a class scope through inheritance. There's even the empty base class optimization to make this as cheap as possible.
But if I wanted to do the same with a non-empty base class, I would be tempted to employ something like:
struct Bar {
using struct Foo;
};
But, alas, that's not supported by C++. My question is, is there another way to achieve the same which I overlooked?
To provide a more complete example:
struct Foo {
enum { some_constant=42 };
// data members follow here ...
};
struct Bar {
using class Foo; // this doesn't compile
int f();
};
int Bar::f() {
return some_constant; // I want to use the constant directly, without Foo::
}
One clumsy way could be to split the definitions in Foo into two classes, one with the constants (which would be an empty class I could derive from without penalty) and the other with the data members, but that looks rather like an inelegant hack to me.
If there isn't a clean way to achieve this, maybe someone can provide a rationale for why it doesn't exist, or perhaps shouldn't exist.
Deriving from a class brings all names from the base class into the scope of the derived class.
Let me stop you there. Yes, it is true that inheriting from a base class causes the (non-private) names in the base class to be accessible from the derived class definition. However, that's not why you inherit from a base class; that's merely the mechanism by which inheritance achieves its goal.
To publicly inherit from a base class is to make a statement about the relationship between the derived and base classes. You're saying that every instance of the derived class should behave like the base class in virtually all ways. Even virtual function overriding still carries with it the expectation that the derived class implementations of these methods are conceptually doing the same job, just in a way appropriate for that derived class.
This is true even of mixin-style base classes, where the base class is used to define common functionality that is imported into a particular derived class. In such interfaces, there is little expectation of a user explicitly talking to base class definitions. But this provision of common functionality is ultimately still based on the semantic idea of a derived class being a base class. And that's very important for many of them to do their job.
Consider what is probably the most prominent mixin in the C++ standard library: std::enable_shared_from_this<T>. It has non-static data members, without which it couldn't actually provide the functionality it does (well, it could, but you would have to provide some interface in your derived class to store them, so it may as well do it).
This is true of private inheritance, though there is some modification. While to the outside world, the derived class is just a derived class, to the class definition itself, it still remains a base class. It remains wholly a base class, along with all the baggage that comes along with it.
Do not mistake the mechanism for the meaning. Mechanisms are important; don't get me wrong. But those mechanisms exist to facilitate meaning.
Having a class contain everything of some other class except the non-static data members is, semantically, nonsense. It doesn't mean anything about the relationship between the types. And you've essentially admitted that the main reason you want this is so that you don't have to scope-qualify the names defined in the "base" class.
This is a mechanical reason, not a semantic one. You shouldn't employ a semantic tool like inheritance to escape the mechanical consequences of how you have chosen to design your types.
In reference to your specific example you could make the constants you want to access static, which will allow you to access them from the second class by fully qualifying with the "base" class

How to create a class which uses member functions defined in another class C++

I'm new to object oriented programming and am struggling a bit with how best to write classes.
I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.
My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:
class Life
{
public:
CoordinateArray LiveCells;
Life();
};
When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.
To answer your question simply and in a pragmatical way, yes, if you want your Life object to have some member functions they need to come from somewhere, the most straight forward way is to derive it from a class containing those member functions, composition does not transfer members to the owner, inheritance does that:
class Life : public CoordinateArray
{
public:
Life();
};
Now you can use your Life objects as a CoordinateArray object. If anything is pure virtual in the parent class you will indeed need to implement it in the derived class, but even if something is not you can still reimplement it in the child class to overwrite the parent behaviour.
I avoided conception and design problematics on purpose, this is mainly a technical answer, judging this from a design point of view requires more context and has some subjective side too so that's another story altogether.
It would be useful to see the declaration of CoordinateArray. However, I suspect you need to make public methods in CoordinateArray. If the methods are declared private (i.e., they come after private: in your class declaration), then they can only be used inside the class's own scope. If they're declared public (underneath public:), then they can be used in any scope. (As a sidenote, there is one other classification, protected, which means they can be used by the class and any of its subclasses.)
In order to initialize co-ordinates of some live cells declare the class CoordinateArray LiveCells public to Life
class Life::public CoordinateArray{ }

C++ assigning an object to another class

I am trying to create a pointer to a class as follows.
ASTNode* pAssign = new ASTAssignmentNode();
However, pAssign does not consist of the variables defined in class ASTAssignmentNode . Am I missing out on something here? How can I access the variables defined in ASTAssignmentNode() ? ASTAssignmentNode() inherits from ASTStatementNode() which inherits from ASTNode().
When writing pAssign->variable (which is declared in ASTAssignmentNode()) an error occurs "pAssign does not contain definition for member variable"
I am not experienced in C++.
Would appreciate any help.
You should use ASTAssignmentNode* pAssign instead. If you're doing this for a class assignment and they give you files you aren't supposed to modify that make you utilize ASTNode*, ask your TA about it because I've been in that situation and there should be workarounds you can use but it will differ from different assignments.
Try casting to access variables belonging to ASTAssignmentNode class
((ASTAssignmentNode* ) pAssign)->variable
What I have used is called a regular cast. You may also use static cast or dynamic cast has mentioned by M.M. If you want a detailed breakdown of which type of cast you need, check out a post here.
As long as you are certain ASTAssignmentNode is a child of ASTNode there should be no implications.
When you cast ASTAssignmentNode to ASTNode it will only contain the class definition for ASTNode and it knows nothing about ASTAssignmentNode. That is why you need to cast it back.
An exception to this are virtual functions. Virtual functions call the child class implementation if they exist.
Since pAssign is a pointer to the base class, you will need to cast it to the derived class, ASTAssignmentNode. Preferably with a c++ dynamic_cast.
dynamic_cast<ASTAssignmentNode*>(pAssign)->variable

Accessing public methods of a Class in a given scenario - C++

Consider a scenario(C++):
Class A, Class B, both derived from same parent class. For every instance of Class A, there is exactly one instance of Class B.
Class A keeps the pointer to Class B, such that instance of Class B is created in the Constructor of Class A.
Basically, in the implementation, Class A provides a way of accessing data from a file(XML). In fact, the methods in Class A in turn calls methods of Class B to retrieve or set value in the XML. For example, Class A has a getter function for retrieving tag value, after doing some operations at Class A level (mostly validations), Class A delegates to the getter function of Class B.
void GetXMLTagValue (const string& sTagName, string& sTagValue)
Question:
In a certain scenario, I got an instance of Class B alone. And I need to invoke a public non static method of Class A. Is there a recommended way of achieving this?
Well the easiest way would be just keep a pointer back to A. It'll be easy beacause A constructs B.
Nevertheless, it's worth questionning yourself about the design intention that's behind this special scenario.
You seem to implement the proxy design pattern, where A is the proxy (GUI ?) and B the real subject (persistent business object ?). The common base class is the interface of both the real object and its proxy. And A forwards the requests to B.
In principle the goal of the proxy is to provide a surrogate/placeholder to control access to the real object (Gang of 4). Your special scenario is a little bit different, as B forwards something to A:
What's the intent ?
must A be informed of some status changes of B ? In this case, I'd suggest to use the observer pattern and see the A function to be called as the (virtual) callback function. The advantage is that if you later come to the conclution that another object needs to be informed, it'll be easy to evolve.
does B take responsibilities that A doesn't have ? Should B manipulate A in a more extensive way ? Then you could see B as being a decorator. It works a little bit like a proxy. If you adopt the decorator approach, you could have other intermediary objects being plugged between the final client and B as between B and A. But seeing your one to one relationship and the fact that A creates B, this would be a more radical change in the design than adding observers; I'm not sure that it's what you're looking for in your design.

What's the best way to access the internal data structure within a class?

I have a class A consisting of a bunch of internal data structures (e.g. m_data) and a few objects (e.g. ClassB):
class A
{
public:
...
private:
int m_data[255];
ClassB B[5];
}
What's the best way for B to access m_data? I don't want to pass m_data into B's function..
// updated:
Many thanks for the responses. Let me provide more contextual info.
I am working on an AI project, where I got some data (e.g. m_data[i]) at each time step. The class A needs to buffer these information (m_data) and uses a list of B's (example updated) to make inference. Class B itself is actually a base class, where different children derive from it for different purpose so I guess in this context, making B a subclass of A might not be clean (?)..
friend class ClassB;
Put this line anywhere in A's declaration if you want ClassB to access all of A's protected and private members.
One of:
Make ClassB a friend of A
Make A a sub-class of ClassB and make m_data protected rather than private
[In response to Mark B's comment]
If ever you feel the need to resort to a friend relationship, the design should be reconsidered - it may not be appropriate. Sub-classing may or may not make sense; you have to ask yourself "Is class A and kind of class ClassB?" If the question makes no sense intuitively, or the answer is just no, then it may be an inappropriate solution.
Ideally, you don't allow external access the data structure at all. You should rethink your approach, considering more the question "What are the functional requirements / use cases needed for ClassB to access instances of A" rather than offloading the management of the internal members to methods not managed within class A. You will find that restricting management of internal members to the class owning those members will yield cleaner code which is more easily debugged.
However, if for some reason this is not practical for your situation there are a couple possibilities that come to mind:
You can provide simple get/set accessor methods which, depending upon
your requirements, can be used to access either a copy of or a
reference to m_data. This has the disadvantage of allowing everybody
access, but does so only through well defined interfaces (which can
be monitored as needed).
ggPeti mentions use of friend, which may work for you, but it gives ClassB access to all of the internals of A.
A getData() function that returns m_data.
Use setData() to change the value.
So in the function in class B you would create a pointer to the class type A variable that you created. Lets just call this pointer 'p'.
Just do p->getData(), p.getData() may be the answer. I think they do the same thing but c++ uses the '->' and some other languages use the '.'. Don't quote me on that one though.
Good luck, sir. Hope I helped ya.
What's the best way for B to access m_data?
Depends on the use.
This is how would I do it :
class ClassB
{
// ...
void foo( A &a )
{
// use a's data
}
};
class A
{
//...
int m_data[255];
ClassB & B;
};
Depending on the implementation, maybe ClassB is not needed at all. Maybe it's methods can be converted to functions.