Initialization without recursion [closed] - c++

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.

Related

C++ best way to create constructor and class instance [closed]

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.

Infinte constructor loop [closed]

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.

Best way to call super class constructor or method is? [closed]

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 8 years ago.
Improve this question
i need to get clear about, the best way to call the super class constructor/method explicitly.
I tried with the following both way to call superclass constructor:
Myclass::Myclass(int a, int b):X(a),Y(b)
{
// do something
}
and
Myclass::Myclass(int a, int b)
{
X = a;
Y = b;
}
So my question over here is:
Which is the best way to call super class constructor/method explicitly?
And what are the benefits will get in both way?
what is the best practice and why?
There is any performance issue lies with both way?
Regarding my question i found this link:
What are the rules for calling the superclass constructor? but still i have little more doubt what i asked above.
if there is any online tutorial, blog or video also u can mention over here, it will great help full for me. Thank in advance.....
The only correct way to call superclass's constructor is from the initialization list:
Myclass::Myclass(int a, int b)
:X(a),Y(b)
{}
The other way in fact calls different constructors:
Myclass::Myclass(int a, int b)
// implicit :X(),Y()
{
// These two don't call constructors but actually declare variables
X(a);
Y(b);
}

Why C++ allows returning a reference to private members [closed]

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 9 years ago.
Improve this question
class test {
public:
test(int value = 0): x(value) {}
int& get(){
return x;
}
private:
int x;
};
this will allow client code to mutate the private members
this is legal in C++, but why ?
Is there any situation where you would actually need to break the class encapsulation ?
Make a member as private, means you can not access it directly. But nothing restricts you to access it indirectly via a public member. It depends on you design. You can even do this:
class test {
public:
test() : x(y) {}
int &x;
private:
int y;
};
In your class, assume you want count how many times a member is read/write. So, you can make it private then put a member function which returns a refernce to the variable:
class test {
public:
test(int value = 0): x(value), count(0) {}
int& get(){
count++;
return x;
}
private:
int x;
int count;
};
I hope this example shows how making a member as private and then putting an indirect access to it can be useful.
Ffirst of all let's consider implementing what you describe. It would be very onerous to properly do so. Your example is easy enough. But what if the reference flowed through a number of functions before it reached the function that exposed it? The compiler would have to do exceptionally complex static analysis, beyond the levels of static analysis that are reasonable to expect from compiler writers.
So even if the designers wanted to ban this, it would not have been tractable to do so. Would the designers have wanted to stop this? Very doubtful. Had they done so, how would the [] operator be implemented on a container or a string?
Is there any situation where you would actually need to
break the class encapsulation
As example of the [] operator on containers and strings shows, this feature is in fact used to support encapsulation.
Why? Because C++ mainly tries to let you do whatever you want and not get in your way; it doesn't try very hard to keep you safe. If you want a safe language, use something else. You have something like object-orientation if you want to, but if you want to break out of that, more power to you. With great power comes great responsibility.
It's worth nothing that you don't even need this to break encapsulation; you could simply reinterpret a pointer to "test" as an integer and access the private field this way.

C++ Reference Length Performance [closed]

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.