New answers tagged

2

If you donot like the additional constructor arguments for the dependencies you need a DI-Container to handle the instance creation for you. You can use either an existing di-container framework or implement a poor mans version on your own public PoorMansDiContainer : IPoorMansDiContainer { private IService mService = null; private IFooService ...


5

For trivial examples, any form of additional overhead will appear massive. The benefit of separating into TUs is that you know that everything in the file is specific for the platform and you can use platform functionality in convenience functions without having to be careful about surgically placing it in the correct preprocessor sections. This also helps ...


0

Apart from performance etc. ... Assume that your base class has a method doSomething. Assume that your derived class doesn't care about doSomething whatsoever. The developer has forgotten that it even exists. The developer of the derived class also wants to create a method that does something and call it doSomething, dosomething, do_something or something ...


5

Java With respect to Java, your premise is completely flawed: you never have to specify that a function is virtual--all functions are virtual by default. Java does provide final to specify that a method can't be overridden, which has a somewhat similar effect, but isn't really identical. To the extent that final means "not virtual", it's still done in the ...


2

You should consider: the type of the graph the operations you need For a simple graph, as opposed to a multigraph, the edges form a set (each edge is an unordered pair of distinct vertices) so you could also consider std::set<node *>. A set is a good choice also if you have to maintain an order among edges. vector list set ...


-1

I'll step your through how I think I see it: Let's say we have a base class A and subclass B. When B is instantiated an A object is also created and contained within the B object. When we try and assign the B object to an A- type pointer/reference/etc, we slice away the B part of the object, effectively only being left with the subObject (A). Therefore ...


0

Surely "b" now points to the correct object so that when we call b.doSomething, we know which method needs to be called. Surely not! The key problem is if b points to or references a base class but in actuality is a derived class, it is the doSomething method defined in that derived class that should be called, rather than the than doSomething method ...


12

Because virtual functions have a runtime performance cost, and part of the philosophy of C++ is "you don't pay for what you don't use." Specifically, virtual methods have to dereference a pointer to find out where the correct method is for the specific object they were called on. One pointer dereference per call may not sound like a lot, but this also ...


0

I would use one of our successful projects as example. Sentilo Sentilo is (in bottom lines) a data concentrator that stores milion of entries from any sort of sensor, gadtget or client. It store data into noSql db and the way to do this is by Restful and stateless webservices. Which accepts json as data representation. Then offers also webservices to serve ...


0

This answer will fall into the category of "suggest a better strategy". Gathering stats on infrastructure assets (not just servers) is what I am currently doing for a living in a global financial services leader. I am trying to understand why one would avoid using a database to hold the bits that are gathered. If cost is a concern there are open source ...


3

If you're talking about variables of user-defined polymorphic types, then in C++ you need to use a pointer or a reference in order to achieve runtime polymorphism. The exact syntax you're describing is probably legal in C++ (hard to say since you didn't give a complete example), but results in "object slicing" rather than polymorphism. The reason is that a ...


1

If you need to be able to assign a subclass instance to a variable in c++, and you need reassignment, then what you want is a pointer. private: State* current_state; If there's ownership involved, you should use a smart pointer like unique_ptr or shared_ptr. shared_ptr most closely matches the semantics of Java references, other than the fact that it ...


2

This is a simple directed acyclic graph, which means that evaluating the nodes shouldn't be terribly complicated. The algorithms mentioned in the "Topological sorting and recognition" section of the Wikipedia article allow you to break the graph evaluation into a linear sequence of steps. Also see this answer.


4

Comments turned into an answer: You are right to worry about performance with locking everything under one mutex, but the better solution is to make sure there is as little going on as possible inside the lock. Thread 1 should have the value and index ready and really only be doing a single write. Thread 2 would operate on an unshared local instance of the ...


2

In your particular case (all variables being scalars, i.e. integral or boolean) you might consider using the atomic facilities of C++11. You need a recent GCC or Clang compiler. So you would use std::atomic_bool and e.g. std::atomic_int etc... for the types of these variables and use atomic_load & atomic_store. A simple usage would be to systematically ...


0

Like @bbjbaand said, I did put common code inside dedicated library, works perfectly!


2

It's certainly not a bad practice to keep the library configuration elements grouped in a common configuration header. On the contrary ! It eases portability to other environments/architectures and facilitates maintenance/deployment. And the application configuration could be different from the library configuration. The only issue is to avoid name ...


1

A compiled library calling a callback, which is a user defined member function of a user defined class. This is possible in Objective-C, and it makes user interface programming a breeze. You can tell a button: "Please, call this method for this object when you are pressed", and the button will do so. You are free to use any method name for the callback ...


0

This is an old question, but since no one has mentioned it, I'll add list (and now dict) comprehensions. It's easy to write a one-liner in Haskell or Python that solves the Fizz-Buzz problem. Try doing that in C++. While C++ made massive moves to modernity with C++11, it's a bit of a stretch to call it a "modern" language. C++17 (which hasn't been released ...


3

Preliminary remark In C++ a struct is in fact a class with all members being public. So you could define it more simply: struct MyStruct{ int x; //... etc. }; // no need for typedef here ! Pass parameter by const reference to the constructor ? This being said, the way you use it in your constructor makes in fact a copy of your struct ...


3

In this case, your settings struct and the object you want to construct with those settings share the same lifetime: the duration of a call to theFunction. So the best option is probably the simplest one: don't even bother giving them separate variables in the first place. In modern C++, that could be as concise as: MyClass mClass({ /* struct arguments */ ...


0

The use of final is not in any way a violation of SOLID principles. It is, unfortunately, extremely common to interpret the Open/Closed Principle ("software entities should be open for extension but closed for modification") as meaning "rather than modify a class, subclass it and add new features". This isn't what was originally meant by it, and is ...


2

There are 2 very different kinds of optimisations. The first is micro-optimisations. These are things like (e.g.) changing x = (y * 4 + z) / 2 into x = y + y + z / 2, or x = y % 8 into x = y & 7. Compilers are very good at micro-optimisations, so don't bother. The second is algorithmic optimisations. Things like replacing "array of structures" with ...


-1

My understanding is that you want to "encapsulate" the arguments you pass to a function - the function should be able to modify only what you want it to modify. Always passing a reference and putting const in front of it is tedious and prone to errors. Also, always passing references would mean creating a local variable for each function argument (instead ...


4

For basic types, reference parameters usually offer no performance attribute at all. Memory For instance, in your example, the char requires a single byte. A reference type requires a pointer, which is usually either 4 or 8 bytes, where the size of a pointer directly correlates to the type of executable you are using (4 bytes for 32 bit, 8 bytes for 64 ...


3

I think you have a wrong understanding about optimization, so here are some facts about it: First of all, optimization is completely irrelevant for 99% of your code! That is the most important fact about optimization: The vast majority of any code is executed so seldomly, that there is virtually no payoff in optimizing it. Thus, the most important skill ...


0

Other answers are good. I can only add that There are speedups that the compiler can do, so you should not bother with them, like reordering instructions or juggling registers to save memory fetches. There are speedups that only you can do; the compiler cannot do them, like invisible I/O you never suspected, or too much memory management. So what I do is ...


7

When I need a class, I'll write a class. If I don't need subclasses, I don't care about subclasses. I make sure that my class behaves as intended, and the places where I use the class assume that the class behaves as intended. If anyone wants to subclass my class, I want to fully deny any responsibility for what happens. I achieve that by making the class ...


-1

There is a little logical difference between template fuction and function template. Function template is the one that could be used to create a family of functions with different argument type. Syntax- template return type function_name (arguments of type T) {...... } A function generated from a ...


4

Let's imagine that the SDK for a platform ships the following class: class HTTPRequest { void get(String url, String method = "GET"); void post(String url) { get(url, "POST"); } } An application subclasses this class: class MyHTTPRequest extends HTTPRequest { void get(String url, String method = "GET") { requestCounter++; ...


0

1.Tiny changes There's no magic available for this aspect: either you can define the execution as a set of more primitive virtual functions that you can override for tailoring purpose; or you can use a policy based design using to obtain the same effect, but at compile time (but with similar structural issues as above) or you could consider feature ...


30

I'm surprised that no one has yet mentioned Effective Java, 2nd Edition by Joshua Bloch (which should be required reading for every Java developer at least). Item 17 in the book discusses this in detail, and is titled: "Design and document for inheritance or else prohibit it". I won't repeat all the good advice in the book, but these particular paragraphs ...


1

To me it's a matter of design. Let's suppose I have a program that calculates salaries for employees. If I have a class that returns number of working days between 2 dates based on the country (one class for each country), I will put that final, and provide a method for every enterprise to provide a free day only for their calendars. Why? Simple. Let's say ...


1

Final effectively means that your class is safe to change in the future without impacting any downstream inheritance based classes (because there are none), or any issues around thread safety of the class (I think there are cases where the final keyword on a field prevents some thread based high-jinx). Final means that you are free to change how your class ...


57

It avoids the Fragile Base Class Problem. Every class comes with a set of implicit or explicit guarantees and invariants. The Liskov Substitution Principle mandates that all subtypes of that class must also provide all these guarantees. However, it is really easy to violate this if we don't use final. For example, let's have a password checker: public class ...


21

One of the reasons final is useful is that it makes sure you cannot subclass a class in a way which would violate the parent class's contract. Such subclassing would be a violation of SOLID (most of all "L") and making a class final prevents it. One typical example is making it impossible to subclass an immutable class in a way which would make the subclass ...


7

The second reason is performance . The first reason is because some classes have important behaviors or states that are not supposed to be changed in order to allow the system to work. For example if i have a class "PasswordCheck" and to build that class i've hired a team of security experts and this class communicates with hundreds of ATMs with well studied ...


127

final expresses intent. It tells the user of a class, method or variable "This element is not supposed to change, and if you want to change it, you haven't understood the existing design." This is important because program architecture would be really, really hard if you had to anticipate that every class and every method you ever write might be changed to ...


1

If you can't do dynamic allocation, you must statically allocate all possible ImageImpl instances that could be returned by FontImpl::GetImage and return a pointer to one of those based on the parameter that gets passed in. For example: static ImageImpl image_a; static ImageImpl image_b; : static ImageImpl image_z; Image* FontImpl::GetImage(char c){ ...


0

The while (!ifstream.eof()) loop doesn't work, because streams/files in C and C++ don't predict when you have reached the end of the file, but the rather indicate if you have tried to read past the end of the file. If the last line of the file ends with a newline (\n) character, then most read action will stop reading when they have encountered that ...


0

However, C++ programmers note that what always happens is that cin.eof() doesn't return "true" until after the last line has been read twice. That is not what is happening. The eofbit plays no a role in the conversion to a boolean (stream::operator bool (or operator void* in older c++)). Only the badbit and failbit are involved. Suppose you are reading ...


1

Advice 1: Consider using std::unordered_map (explanation on en.cppreference.com) if you need fast lookup and don't need sorting by key. In C++, std::unordered_map is an implementation of the hash table that you have learned from the "data structures and algorithms" class. On the other hand, std::map is a balanced binary search tree. Advice 2: Given a ...


6

The common object-oriented approach for hiding implementation details (in this case A_algo and B_algo are implementation details) is to find a connection between the two (or among three or more) functions and to define a new generic interface (in C++ a pure abstract class), which is then instantiated by some sort of a factory. In object-oriented terms, this ...


1

The Factory Pattern is used to handle similar situations, but in the context of OOP. You would essentially have a standalone class for each algorithm, an interface they implement so they can be used interchangeably, and a method that uses arguments (the user's input, in this case) to decide which class to instantiate. Your function pointer solution is ...


1

Generating for all possibilities did not look to be a very good solution to me. The key and values may be objects as well. Hence, the possibilities are infinite :( Did you have a look at IMapImpl class? This class does not use types but the binary data (which is provided after serialization). Hence, another solution would be writing an API that mimics this ...


1

IMO threads can be split into three main categories. Long running threads that monitor one thing per thread. Putting a limit on these will limit the number of things you can monitor which is likely not what you want to do. If you do put a limit it should be very high and mostly a sanity check. Threads that spend most of their time on computation. You ...


23

A better concurrency story is one of the main goals of the Rust project, so improvements should be expected, provided we trust the project to achieve its goals. Full disclaimer: I have a high opinion of Rust and am invested in it. As you do in the question I'll try to avoid value judgements and describe differences rather than (IMHO) improvements. Safe and ...


0

You cannot practically hide anything from a determined programmer, but you can create an abstraction layer to hide the details of your implementation from a casual user, for various purposes. For additional details, search for Proxy and Adapter pattern articles. Depending on the requirements of the original API it might not be possible to completely hide ...


1

If I understand your question correctly, you would like to obfuscate the protocol, but not necessarily masquerading the nature (purpose) of the software to be built by the hired C++ developer. You can consider using protobuf and focus your mass-renaming efforts on just the message and field names. The hired C++ developer will use one set of names and the ...


3

In your example the instance Object* BaseClass = new Actor(); gives you an object about which all you know is that it can do what another instance of Object can do. The instance itself has all the knowledge of an Actor. If you call a method on BaseClass (say a method called ToString()) it will be an Actor.ToString() not a Object.ToString() you call. If ...



Top 50 recent answers are included