Object-oriented programming [closed] - c++

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am developing a project in C++. I realised that my program is not OO.
I have a main.cpp, and several headers for different purposes. Each header is basically a collection of related functions with some global variables to retain data. I also have a windowing.h for managing windows. This contains the winMain() and winProc(). It calls the functions that resides in my main.cpp when events happen (like clicking a button) or when it needs information (like 'how big to make this window?'). These functions are declared in a seperate .h file included into windowing.h.
Is it worth changing this to be OO? Is it worth the work. Is there any better way I can construct the program without too many changes?
All feedback welcome, thankyou for taking the time to read this.

No, I think if it ain't broke, don't fix it.
Any windowing system is inherently OO to a degree. You have a handle to a window managed by the OS, and you can perform certain operations on it. Whether you use window->resize() or resize(window) is immaterial. There is clearly no value in such syntactic rearrangement.
However, as the application grows, you will likely find that many windows are mostly similar and subtly different. The best implementation is boilerplate basic functionality with special functions attached. And the way to do that is with a base class and polymorphism.
So, if you can refactor the program to be more elegant with OO, go for it. If it grows into the OO paradigm with natural evolution, follow best practices and let it be so. But don't just try to be buzzword-compliant.

Two things you need to think about: cost/benefit analysis and opportunity cost.
What is the cost of changing your code to be OO? What is the benefit? If the latter outweighs the former, then I'd tend towards changing it.
Costs include traditional costs such as time spent, money spent and so on. Benefits include a cleaner implementation, leading to easier maintenance in future. Whatever other costs and benefits there are depend really upon your own situation.
But one thing often overlooked is the opportunity cost. This is a cost that should be factored in to your analysis. It's an economic term meaning foregone opportunities.
In other words, if you do convert your code, your cost includes your inability to do something else with that time.
Classic example. If you do the conversion and a customer decides to not buy your software because you're not adding the feature they want, that lost sales opportunity is a cost.

It depends on what you want to accomplish with the project. If not using the OO features of C++ works for you and there are no good reasons to change, then keep going the way you're going. If, on the other hand, you would like to learn more about OOP and you have the time to apply to it, refactoring it to be more OO style will provide you with a great learning opportunity.

I would follow the best practices for working with whatever window manager you are using. Most use an OO style, which you'll automatically inherit (!) as you follow its usage patterns.

Related

Writting a C++ Dll and exposing it efficiently to .NET (not through C++/CLI) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am building a C# project. This project is going to use NVidia's Tesla through CUDA. CUDA C native implementation is not exposed directly to C# and, in my opinion, the available C# wrappers (like Brahma, CUDAfy, Linq to GPU) are not mature enough for production.
I decided to go ahead and build my math logic in a C++ component that is going to access CUDA which is the official supported way. C++/CLI is not an option as I am using Intel C++ Compiler, for performance, which doesn't support CLR extensions.
My most important criteria is performance, so, I would try to minimise marshalling and copying arrays between C++ (where my business logic lives) and .NET (the rest of my applications).
I am aware that this question has been asked before, but mostly, the C++ library is already there and other times, C++/CLI is an option, but here, both situations are not the case.
Given that I am going to write the C++ library from scratch in C++, I am in the position to decide the best way to expose it to C#. Do you have any recommendations or best practices that I should follow to get the easiest and highest performing integration between C++ and .NET? Note that what I will be exchanging are mostly large arrays
Edit: clarifying that I am building my business logic (math) in C++ and not an infrastructure library to facilitate access to GPU.
While it is certainly possible to outperform the already existing libraries that you deemed not mature enough, the very fact that you are asking this question here should make you think twice about deciding to roll your own library/implementation!
Considerations beyond specific performance such as stability and reliability should be your primary concern if this is going to production. Generally unless you know what you're doing, duplicating the effort of the community, or other teams of developers, can be a slippery slope.
I know this answer doesn't really address your question but as it's formulated your question is in my opinion overly broad and there is no simple answer. Initially I was going to post this as a comment but decided it was too long to fit the format.
So, in closing, I recommend you try out the already existing libraries and if you find them not-fitting from a performance stand point, start asking specific questions.
UPDATE
If you're going to implement most of the logic in C++ and you're expecting to just be transferring some results back to your managed code in the form of arrays then there isn't much that you need to do. In general the automatic marshalling of arrays is as efficient as you're going to get.
The one thing I would recommend is though to read as much as possible about Marshalling and use a performance profiler before deciding to get "creative" in order to improve things.
And here's one last idea that might be interesting but again, you should profile before attempting to use this: you might try to use a Memory Mapped File as the backing store for your data and open the file from both ends. Ultimately this may or may not be useful so definitely profile before you buy ;)

Why c++ is not used in L2/L3/L4 development projects [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have been involved in numerous c++ projects mainly in the application domain pertaining to VOIP protocols. Now I have to move to L3 , L2 protocol development projects where I found 'C' is preferred language of choice for the L2/L3/L4 developers.
Now I am wondering expect device firmware related applications, why protocols are developed using stone age era language. Why ppl dont take the benefits of OOPS techniques? Will it be prudent if I try to convince them to switch to c++. Most of the developers working in the team are C experts and not comfortable with C++.
There are several reasons for continuing using C.
There are existing C projects. Who will pay for converting them into C++?
C++ compiler (of a good quality) is not available on every platform.
Psychological reason. When you pass and return objects by value, temp objects are created left and right. This is not ok for small systems. People do not really understand that passing and returning references completely solves this problem. There are other similar issues.
And finally. What is wrong with C? It works! (Do not fix what is not broken).
It is possible to write the same performant code on C++ as on C, but this requires better understanding, training, code control discipline. Common percetion is that these flaws are unavoidable.
If you think of C as simply a "stone-age language," then I think you misunderstand why people continue to use it. I like and use both C and C++. I like them both for different reasons, and for different kinds of problems.
The C language presents a model of the computer that is both (mostly) complete and very easy to understand, with very few surprises. C++ presents a very complex model, and requires the programmer to understand a lot of nuance to avoid nasty surprises. The C++ compiler does a lot of stuff automatically (calling constructors, destructors, stack unwinding, etc.). This is usually nice, but sometimes it interferes with tracking down bugs. In general, I find that it's very easy to shoot yourself in the foot with both C and C++, but I find the resulting foot-surgery is much easier to do in C, simply because it's a simpler language model.
The C model of a computer is about as close to assembly as you can while still being reasonably portable. The language does almost nothing automatically, and lets you do all kinds of crazy memory manipulations. This allows for unsafe programming, but it also allows for very optimized programming in an environment with very few surprises. It's very easy to tell exactly what a line of code does in C. That is not true in C++, where the compiler can create and destroy temporary objects for you. I've had C++ code where it took profiling to reveal that automatic destructors were eating a ton of cycles. This never happens in C, where a line of code has very few surprises. This is less of an issue today than it was in the past; C++ compilers have gotten a lot better at optimizing many of their temporaries away. It can still be an issue, though, and especially in an embedded environment where memory (including stack space) is often tight.
Finally, code written in C++ often compiles slowly. The culprits are usually templates, but eliminating templates often makes your C++ code look a lot like C. And, I really cannot overstate how much this can affect productivity. It kills productivity when your debug-fix-recompile-test cycle is limited by the compilation time. Yes, I know and love pre-compiled headers, but they only do so much.
Don't get the impression that I'm anti-C++ here. I like and use the language. It's nice to have classes, smart pointers, std::vector, std::string, etc. But there's a reason that C is alive and kicking.
For a different perspective, and one that is firmly anti-C++, you should at least skim over Linus Torvald's perspective on C++. His arguments are worth thinking about, even if you disagree with them.

What C++ refactorings do you use in practice? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm going to create the comparison table of existing automated C++ refactoring tools as well as explore an ability of creation of such tool, free and open-source.
My question is: what refactorings do you really use in your everyday work? There are obvious things like renaming variable/class/method, but is there something specific for C++, like dealing with templates, STL, copy constructors, initializers, etc., etc?
I'm interested in building of realistic picture of all that little problems that C++ developer is facing each day in his coding and that could be automated at least in theory. I'm talking to my colleagues but that's probably not enough.
Thanks in advance.
It is pretty clear from the answers that few C++ programmers have ever seen a real refactoring tool. Yes, they are quite rare and highly specific to the IDE you use. That's inevitable, there is otherwise no good way to find out what source code files contribute code to the final executable. The preprocessor makes it extra challenging, you need to know the macro values. A source code parser is required but not enough.
Visual Assist for VS is one I know of.
As you said there are obvious things:
renaming is one
altering a function signature is another (especially since a function is almost necessarily duplicated: declaration in the header and implementation in the source)
renaming / moving a file (update of include directives)
Note that though it's basic, it's rarely well dealt with. My primary complaint being that comments are generally not updated (I am so not speaking about doxygen auto-generated useless clutter). So if I was describing the use of the class within a header, or the justification of using this class in another source file, the comment is now obsolete because by renaming the class no one will now know what it refers to...
There are however much more interesting cases:
When changing a function signature, you need to update all the call sites, the developer will need help for localizing them
With inheritance, the ability to act on all classes of a hierarchy: changing a function signature (once again) or adding/removing a virtual override.
With template: the Concept proposal having been dropped, it would be good if you could synthetise the requirements on the type passed (methods / inner types necessary) so that when altering those requirements (by modifying the template definition) one gets notified of the list of classes that are in use by this template and no longer conform to it (and shall be updated). Note that in case it's just renaming the type / method, you might want to automatically propagate the change, as long as it doesn't break anything else.
Good luck...
Take a look in Martin Fowler's Refactoring: Improving the Design of Existing Code and Refactoring to Patterns by Joshua Kerievsky. These in turn reference the GoF Design Patterns book so get that too.
If you can beyond the basic Rename Feature and Extract Function then you might be onto a winner.
Here's a C++ design pattern I came up with yesterday: Ditch inheritance in favor of policies.
One refactoring that I wish was supported is actually inject method. More-or-less the opposite of extract method.
Because perhaps I see that I can then rearrange the resulting code to better clarity or effect; but I am not aware that there is tool support for this at present.
Hi i use http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/ with this tool i do renaming variable/class/method, changing function body,initializers

Reasons for refactoring tools for C/C++ to be so limited [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
What is the problem that no industrial level refactoring tool for C/C++ have been created, I only need a tool that "just works"?
What I mean by "industrial level" is a quality provided by JetBrains products (IntelliJ, ReSharper), or above. Any available solutions (including Visual Assist from Tomato Software or Eclipse CDT) are not mature enough.
Below are advantages for a start-up to drive such a project.
alleviation of C++ boring syntax (making development more fun);
C++ is evolving (0x version is coming hence a lot of work for such tool implementers);
marketing niche is broader than anything else (a lot of written C++ code, a lot of active C++ projects), even taking into account Web (HTML/JavaScript) projects;
C++ is chosen for system problems where each bug found by tool at compile time is a survival (a lot of corporations or governments should be interested in);
such tool can decrease project compilation time;
The only drawback is technical challenges... but looking at what Google, Microsoft, Intel, etc. are doing, there should be no unsolvable technical problems.
Lets summarize:
it is possible to implement such product
it is enormously profitable
it doesn't exist
No one wants make a profit? Collusion ;) ? Whats is the reason?
Let's consider just one basic refactoring: Rename function
The implementation appears very simple. Find all references, and replace the identifier used.
It gets a little more complicated with virtual functions. Now it's necessary to find the base declaration (and implementation, if not abstract), and references may be to any derived implementation in the class hierarchy. Much more difficult, but still feasible, because the group of functions to be renamed is well-defined.
That's the complexity that applies to languages like C# and Java. Now comes the kicker: C++ templates are duck typed. The set of implementations in the class hierarchy is no longer well-defined, because it could include ANY function with the same name and possibly compatible parameters. You did remember about Koenig lookup, right?
Trying to separate the list of functions which must have the same name, because they started out in the same overload resolution set, from those truly independent, would be an absolute nightmare. At this point you might as well just do a textual search-and-replace.
So let's go down your list of claims/desires:
"alleviate boring syntax". This is just trolling and means nothing in any technical sense. If the tool doesn't input and output C++ syntax, it's not a C++ refactoring tool.
"C++ is evolving". This means that such a tool would need to be maintained at considerable expense to keep up. It also means that a well-maintained tool would easily steal market share from older stable tools. And it means that any tool needs a ton of user configuration -- you don't want to generate C++0x-isms on a C++03 codebase after all -- so users will have to use the tool an awful lot to win back the time spent configuring.
"Each bug is a survival"? Not sure exactly what this grammatically nonsensical statement means, but perhaps it means zero bug tolerance? But that's best achieved by maintaining stability (the antithesis of automated refactoring that touches multiple files), solid architecture and documentation (which a refactoring tool won't automatically update, or do you want that too?), massive test suites, and static analysis. In fact, refactoring makes the massive test suites even more important, if that's possible, in order to verify that the tool didn't break anything. Note that automated static analysis faces some of the same challenges as refactoring, but since it doesn't change the code it can and does work on post-preprocessed code and/or compiler ASTs.
"decrease compilation time"? This is an unsupported claim in serious need of some evidence or at least solid reasoning. Are you expecting a refactoring tool to introduce pimpl for compilation firewalling? None of the C# and Java-style refactorings will reduce C++ compile time one whit.
"it is possible" No, actually it seems like it isn't. If you or I can't design one basic refactoring like Rename function in a sane manner, never mind implement it correctly, how can anyone implement dozens of them? If it is possible, it's also assuredly extremely expensive, which leads to:
"it is enormously profitable". Profitability requires not only a large base of users who are willing to pay for a product, but that the potential gross sales exceeds the costs. I claim you have seriously underestimated the costs so until you provide some real research on costs and markets I'll call this one wishful thinking as well.
"it doesn't exist". After going to some length to explain why such a tool can't exist, I'm now going to tell you that it already does? Yup. At least insofar as refactoring makes the final code better by doing things like hoisting common subexpressions outside loops, unrolling loops, exchanging order of iteration, inlining, cache optimization, vectorization, they are already provided by optimizing compilers, an area in which C++ leads both C# and Java by a wide-margin. C++ simply doesn't require many of the source-level tweaks needed in C# and Java in order to get a good final product. It's only the manipulation of source code to make it more accessible to humans that remains, and the existing tools do an adequate if not exception job of this.
This link talks about some details and complexity involved
The reason is that C++ is not parseable by most common parsing techniques (LALR, LL, etc.) and actually requires some pretty heavy lifting to properly parse. Some tools like clang and gcc-xml make it possible for other tools to process C++ without implementing their own C++ parsers, although both are fairly new, and it can still be complicated to process C++ even with these parsing tools. I think that the industry will eventually see all the Java-related goodies ported/adapted to C++ ... the question is when.
The problem is that C++ is hard to parse (its grammar is not context free) and hard to make any sense of without actually compiling the source. Java tools can work because the language is a lot simpler, both grammar and semantics.

Does it feel anytime that c++ sometimes reduces problem solving time and increases syntactic, semantic rigor? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
C++ introduces OOPS, templates and variety of other concepts. But sometimes I am stuck in unmanageable storm of calling convention incompatibilities between methods, convoluted casting between distantly connected classes and struggling with code that forces me think in the level of byte-alignment.
I am very tempted to go back to plain old-C language that is low level enough and simple enough that I can spend much of my time solving a problem at hand, than having to figure out the conceptual implementation and nuances of using C++.
What is your take on such an issue. Using C-language as the first class citizen in my code-base and coating it at the end with a C++ primer make for a better way to manage a conceptual code-base ??
sometimes I am stuck in unmanageable storm of calling convention incompatibilities between methods, convoluted casting between distantly connected classes and struggling with code that forces me think in the level of byte-alignment.
It sounds like you might be doing something wrong. I don't know what sorts of projects you work on, but I've rarely had to deal with any of those things--certainly never in over 99.9% of the code I've written--and I've written a bit of C++ code (though not nearly as much as others here on StackOverflow).
What is your take on such an issue.
You should consider getting a good book on C++ (like one of the introductory books or any of the best practices books listed in The Definitive C++ Book Guide and List) and really learn C++ if you want to use C++.
I often feel the way you do. C++ compilers are incredibly bitchy about insignificant details and, if you considered them an object, they have appalling encapsulation, and they give horrendously bad error messages. Sometimes, programming C++ feels like fighting against the Standard.
However, I'd never, ever ditch it for C. If you're considering it, you fail C++. Yes, templates and their syntax and some of their semantics can be a bitch, but the power they offer is unparalleled. The things offered like automatic memory management and the power of the STL just can't be matched by C.
In addition, nobody is forcing you to use templates. You could write a whole C++ program using nothing but the pre-provided templates. You could never use polymorphism, or templates, or encapsulation, or object-orientation as a whole, and yes, sometimes none of those solutions are appropriate. But it's plain stupid not to give yourself the option.
And if you're casting classes in C++ (frequently), it sounds to me like whoever wrote the original code flat out didn't know what they were doing. Same for byte alignment.
I've never had to worry about byte alignment unless I was writing binary files.
Casting distantly related classes to each other is bad design.
I've never worried about calling conventions unless I was writing interrupt routines.
If you forced to frequently "cast distantly connected classes" and "think in the level of byte-alignment" - there is something wrong with the architecture of the project. Language is not the problem here.
C++ is heavy. You probably should not use all the features it provides. KISS principle, you know.
You can always pretend that C++ is just "C with classes" and exploit templates and other "hard" stuff only when it will provide reasonable improvement in some areas (like code simplicity, as a matter of fact).
I recently switched back from C++ to C and took a liking in C99. But it certainly depends on what you are doing. For a library of reasonable size, C99 with its advantages over C89, is good enough, and as somebody else said you can easily provide a C++ wrapper, if necessary. C++, I only would go for a big project that has large amount of code reuse (internal or external) with templates.
Things from C++ I missed in C89 have nothing to do with objects or so, but are simple things as declaration of variables inside the for and a well defined inline feature. C99 has that plus variable length arguments for macros, so I am happy with it.
You are not alone. These are all well-known flaws in C++, a language which forces developers to attend incompatible conventions, to struggle to overcome a convoluted caste system, and to take their code in for byte-realignment every 3,000 lines. Definitely switch back to C.