How to define an object from Class A in Class B - c++

I'm a beginner in C++ programming and I've a (stupid, I think) doubt about how to pass an object's class into another class. Suppose we have these two classes:
class A {...}
class B {...}
and I want to use an object from A into B. For example:
class B {
A ab;
[methods prototypes that include the object ab]
method_B (A ab); //for example
...
}
The question is, can I do this? Does it make sense, thinking about object-oriented programming?
Or, I could define an A's object in main() and after that I would call a method from B that would include A's object as argument?
My question is all about how to use object's from another class into another (functionally independent!) without "violating" the object oriented programming rules.
Thank you for any help,

You can do this. Many libraries and languages do this. From OO view you need to need to design class A such that it will expose (public) a minimal and useful inteface to be used but other classes (such as class B).

Related

Is it a bad practice to intertwine two classes in c++?

I give the following examples to illustrate my question:
class B;
class A
{
public:
class B *pB;
};
class B
{
public:
void perform(A &obj)
{
}
};
In the above two classes. class A has a pointer to class B. class B has a function that will work on class A object. Though it can compile, I was wondering whether this is not a good practice for designing two classes as they are intertwined. If this is bad design, do you have some ideas to avoid it? Thanks.
Having two concrete classes rely directly on one another can get you into trouble.
It is often better to "program to an interface".
There is a long discussion here under the title "Program to an interface, not an implementation", which draws out why decoupling matters
In your example, void perform(A &obj) could instead take an abstract base class that A derives from. It might be worth having an interface that A uses in it's member variable too, but there' no suggested usage in your example to go on.
Why is this "better"? For starters, it will make you think about encapulsation - and what specifically the interface should be exposing.
It will also allow you to use different conrete instantions of the class, say for testing purposes.
If you use an interface, you can change the conrete classes separately... there are many advantages.

Sharing variables between objects of different classes (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...

Alternative to direct inheritance

I have two classes class A and class B. I want class B to have functionality of class A plus some more functionality of its own. One of the very simple ways to do this is to inherit class B from class A. But I cannot do this for some implementation specific reasons.
I have thought of another solution where in I will create another class class C which will contain all the virtual functions. The classes A and B will inherit from class C. The class A will contain the implementation of virtual functions and class B can also define the same set of functions and hence class B will have functionality of class A.
Is this the optimal solution? Are there any better solutions than this other than direct inheriting class B from class A?
What you are looking for is called Composition (over Inheritance).
Composition over inheritance (or Composite Reuse Principle) in
object-oriented programming is a technique by which classes may
achieve polymorphic behavior and code reuse by containing other
classes that implement the desired functionality instead of through
inheritance.
This means that instead of having class B inherit from class A, you can have class B contain an instance of class A. This is also good coding practice to avoid tight coupling between class A and class B.
You can do that however if you create class C to be an abstract base class and have class A and class B inheriting from it, then you realize that class A and class B would be unrelated except for the fact that they inherit from the same abstract base class. That means that you would not be able to cast instances of class B to A, etc. In general such implementation depends on the use cases.
E.g.:
Your class C is Person, class A is Teacher and class B is Student. Then a student is not a teacher and a teacher is not a student, so such implementation is valid.
You can use proxy classes, by creating two other classes PA and PB where PB inherits PA. These proxy classes duplicate the interface of A and B respective, but doesn't actually implement them. Instead they just call the functions in an instance of A and B.
The class A will contain the implementation of virtual functions and class B can also define the same set of functions
This way you'll have code-duplication and it's not a good thing.
If you don't want to use inheritance, try composition.
I explained composition earlier here.

Wrapper design pattern

Say I have a class:
class B;
class A{
public:
A();
virtual B foo();
}
defined in a 3rd party component. I want to wrap classes A and B, resulting myA and myB.
Now, I shouldn't be able to access class A and class B from the outside, but rather have the same functionality for myA and myB. foo() could be called from the 3rd party module.
I would prefer to do this using inheritence, not encapsulation.
So there are 2 problems:
Calling a->myFoo() (need to rename methods because of same signature and different return type) should call A::foo() if a is of type myA.
Calling a->myFoo() should call myA2::myFoo() if a is of type class myA2::myA.
Any suggestions on how to do this elegantly? I came up with some solutions but I prefer a fresh view on the whole thing.
EDIT:
Just a theoretical question. I don't actually need to do this, just thinking of ways it can be achieved.
EDIT2:
myA2 is a class that extends myA. Before the pattern, it would have been called A2 (a class that extended the class A from the 3rd party module).
I don't understand why you prefer to do this with inheritance instead of encapsulation. Generally speaking, extending the class you're wrapping is the "wrong" way to implement the wrapper pattern, especially since you generally want to redefine the interface in the process. In class myA, you'll have a field of type A that contains an instance of class A, which methods in myA can call upon as needed. Unless I've misunderstood what you want to accomplish, this is the most elegant way to accomplish what you want.
You should be able to declare the function names/parameters similarly. Check out:
strange-inheritance section: [23.9] What's the meaning of, Warning: Derived::f(char) hides Base::f(double)? on the 3rd code block.
It also shows the syntax for calling base methods.

How to exchange data between classes?

I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.
So, let's assume we have 4 classes:
class Main_Window
{
//...
void load_data_menu_selected();
}
class Data
{
//...
double *data;
}
class Load_Data
{
//...
double *get_filename_and_load();
}
class Calculate
{
//...
int do_calculation()
}
So, Main_Window is class for application's main window where it interacts with user input etc.
I want to do:
create an instance of class Data in the Main_Window
use Load_Data for loading data from file and store it in the Data
use Calculation class for doing something with read data in Data class
The question is: where I should create classes, to make Data class members available from other classes. Should I use Inheritance?
Start from observing what are possible relations between instances of two classes. Let us say a is an instance of class A and b is an instance of class B. If a uses b, class A can have as its member instance of class B (b), pointer to b (which is of type B*), or reference of b (which is of type B&). If only one method of class A uses b, you have again same three options: B, B* or B& can be method's arguments. Having B* and B& as class members suggests that a does not control b's lifetime so class A must have a method that sets these members through its parameters. The question of ownership (objects' lifetimes) has a big role in design of relationship between classes. Main relationships are briefly described in this article.
I think you only want to have a Main_Window class, and the rest should be members of that class.
class Main_Window
{
private:
DataObject windowData;
public:
void loadData(string fileName);
void calculate();
}
Inside the loadData and calculate methods, you will be able to access the same data with this->windowData . Sorry if my syntax is bad, my c++ is rusty
Typically, you would pass (const) Data& around as an argument. If do_calculation() needs a Data to work with, then it takes Data&. But I can't really be more specific or useful unless you post more of your design.
You need to know how to design in OO. Thinking in C is different from thinking in c++. You can that your classes have many methods. Well, that sound like a bad design.
I can recommend you to start with the SOLID principle.
Then start writing unit tests for your classes. TDD could help you improve your design even further.
It sounds like you should not use inheritance here. The main reason for saying so is that you have a number of classes (Window, Calculator, etc.) using or doing something to an entity (i.e. Data). Inheritance is used to denote an "is a" relationship (i.e. if A inherits from B, A "is a" B).
In this case, you use composition, which denotes a "has a" relationship. So each class takes a reference to an instance of Data, and acts upon that object.
Who owns the Data object? To share a single Data object, you might want to look into Boost shared_ptr, which allows multiple reference-counting pointers to share an object allocated with "new".