Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The design problem is that the constructor of one type creates an object of another type whose constructor again creates a object of the first type.
Definitions:
class A
{
A();
B* b;
}
class B
{
B();
A* a;
}
Implementation:
A::A()
{
b = new B();
}
B::B()
{
a = new A();
}
What would a solution be to this?
The design problem is that the constructor of one type creates an object of another type whose constructor again creates a object of the first type.
Solution to infinite recursion is to not do it.
Either have no (mutual) recursion at all, or terminate the recursion at some point. For example, you could change the design of the classes so that A creates a B, but B doesn't create an A.
Unless you're trying to model something infinite (in which case this is the wrong approach), there should be a finite number of elements in your data structure.
Even if A needs a B and B needs an A, does every A need a B and does every B need a A?
No: Then add a condition (which likely will require adding a constructor argument) that breaks the chain and sets its member to nullptr.
Yes: Does every A needs a new B or could it use an existing one instead (and similarly for the other direction)?
Can use existing: Pass along an existing A or B as needed to break the chain.
Must be new: You're modeling something infinite. Generate data lazily instead.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm pretty new to c++ language however I have experience with python and a little bit with java.
Since c++ is pretty overwhelming and there is like always few ways to achieve certain behavior I have 2 questions related to oop.
What is the best way to create class constructor with parameters?
For example let's say we have sth like that:
struct Test {
int x;
int y;
};
And there are 2 popular ways for constructor:
1.
Test(int x, int y) : x{x}, y{y} { // rest of constructor};
Test(int x1, int y1) {
x = x1;
y = y1;
// rest of constructor
}
Which one should I use and why?
Which style is more like c++ to create class object and why?
Test* testptr = new Test(1, 1);
vs
Test test = Test(1, 1);
The most C++-ish way to create a struct is struct_name{value1, value2}. And you don't need to declare your own constructor.
If you really want to use a constructor, use the one with initializer syntax. Here is the difference. Let's consider a structure with two fields. So it looks like: {one, two}. When you use initializer syntax, you create the needed struct immediately before the actual constructor code you wrote between curly braces. So it looks like: {1, 2} (we have values now). However, when you initialize those fields inside a constructor's body, it will create a structure with default values first and then change them. So it looks like: {0, 0} ...constructor is working... {1,2}.
Ok, the last thing about it is parameter declaration. You should use constant references as it prevents a programmer from changing those parameters inside the function body, and these variables are passed by reference and not copied. Let's look at two examples:
void fun1(int a, int b);
void fun2(const int& a, const int& b);
fun1 here copies those two parameters before using them inside the body. However, fun2 gets only references to the variables and work with their values directly. Also, because of the const, you cannot change them, so it is completely safe.
Modern C++ does not like the new operator. We use it only inside constructors and calling the delete operator in destructors. However, it is not recommended to use the new operator in other cases as it is much harder to prevent memory leaks, and it violates the RAII idiom. If you really must use raw pointers, then consider putting them inside smart pointers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to do a bit of refactoring and I am curious about how would you approach this problem.
Basically I'm trying to create an initialization function for each class. There are classes that inherit from some others, and i would like to use parent initialization function if possible. How would you address this?
I would like to use these structs with memcpy and maybe using also them with the keywords align and __attribute__((packed)); and they must be usable with extern "C". I would exclude then constructors and destructors.
An example to explain:
struct A
{
int a;
};
void initialize(A& a)
{
a = 0;
}
struct B : A
{
int b;
};
void initialize(B& b)
{
initialize(b); // here I want void initialize(A& a), not recursion
b = 0;
};
Maybe I have to do some kind of cast? Ideally I'm looking a solution that does not create overhead.
Use a static_cast.
In your code, the initialize(b) call will recurse infinitely, because b is better matched as B& than as A& (the argument of the function you want to call), thus the overload resolution picks the same function and recurs.
You specified that you want to initialise the A part of the b object. Why not tell that to the compiler? Tell it that you want to call initialise in it as though it was an A, like so:
initialize(static_cast<A&>(b));
As for your concern that you mentioned in the comment - no copies are being made here. If I used static_cast<A>, however, a temporary object would be created, but that's not the case. I am not casting b to an object of a type A. I am casting it to a reference of a type A, which will result in creation of temporary reference. Since A& matches with A& better than with B&, the first function will be chosen, thus avoiding the recursion.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
class A { int* a; };
class B : public A { int*b; };
int main() {
A* ptr = new B();
delete ptr;
}
class A is a pure virtual interface class and class B inherits from class A. When we delete ptr which destructor will be called? The one from the A class or the one from from the B class?
Comment: First of, why do you have code outside any function? Statements only make sense when there are within the body of a function, like main.
Assuming the statements you posted were supposed to go into main:
Answer:
delete ptr will call the destructor of A. The compiler will not 'think' any further than this.
Reason: All methods (including the destructor) are non-virtual by default. In your case, you did not specify that the destructor should be virtual. The compiler sees that you are calling the destructor on a A* pointer, so it calls the destructor of A.
What if I had specified that Class A destructor was virtual? Would it still call the destructor of Class A?
Answer: If it were virtual, it would call the destructor of B, because the actual type of the object would be determined during the execution of the program.
See more about virtual functions and polymorphism here.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In a method of an object of type class A, I handle an object of class B that has a public method .join(*A).
I want my object of type A calling this someObjectOfTypeB.join(*A) method, to use a pointer to itself as the parameter.
void A::someMethod()
{
B b();
b.join(I want to a to use a pointer to itself as a parameter);
}
A a();
a.someMethod();
Upon further investigation, this was not the problem as I led myself to believe; and is indeed the correct way of doing what I wanted to do.
Try using this:
void A::someMethod()
{
B b;
b.join(this);
}
As #AndrewLazarus and #JonathanWakely commented, use B b; instead of B b(). The later declares a function b without parameters which returns B, and that is not what you want.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
My question is simple, what is the performance loss due to reference length. I cannot explain myself but here is the sample:
between this
C* pC = m_a->m_b->m_c;
and this expression
C* pC = m_b->m_c;
I am asking this because I have a global class which has a Singleton pattern and holds everything. I am accessing all of its members from its members like this.
class Global
{
A* a;
X* x;
};
class A { B* b; };
class B { C* c; }; // etc
class X { Y* y; };
class Y { Z* z; };
class Z
{
void foo() { Global::GetInstance()->a->b->c->foo(); }
}
Is this a good design? Any advice for this? I am having some trouble with this topic too Qt Architecture Advice Needed
Every -> operator is an indexed indirection, which costs a cycle or two, depending on the processor, and may be invisible if its pipeline is good enough.
However the real question here is 'compared to what?' What other implementation techniques are you considering for solving this problem? Unless you have a viable alternative your question is really meaningless.
Similarly the frequently-asked question about the relative efficiency of virtual and non-virtual functions is meaningless unless it takes into account how to get the same effect both ways. In the non-virtual case this amounts at least to an 'if' or 'switch', whose cost has to be added in to the comparison.