views:

427

answers:

9

As I read in Thinking in java,

Interface and inner class provide more sophisiticated ways to organize and control the objects in your system. C++, for example, does not contain such mechanisms, although the clever programmer may simulate them.

Is it true that C++ programmer simluate features that java owns,e.g. interface and constraint themself not to step over the boundary,e.g. including non-static-final(non-const) data member within the simluated interface?

Are these features that Java provided natural way for developing software.So if C++ programmers could,they should code and think like a Java programmer?

EDIT: I know that every programming langauge have its own characteristics and its application area and the design of programming language is making tradeoffs.But what I want to know is whether something java introduced for example interface,are better way to help/force programmer think throughly and produce good class design?so C++ programmers would like to simulate some of these features?

thanks.

+15  A: 

C++ interfaces are easy: they're simply classes with all pure virtual methods, including a pure virtual default destructor. (Thanks to itowlson for the correction.)

duffymo
Specifically, interfaces are classes with all **pure** virtual methods -- though this is one area where the C++ idiom is more flexible, because you can have an "interface" that actually has implementations for some of its members (like a Scala trait), which you can't do in Java.
itowlson
Absolutely right, itowlson.
duffymo
Except for that last bit - you can have an abstract class in Java that has implementations for some of its members and abstract for the rest.
duffymo
Which means you can't use it in conjunction with another base class.
Anon.
Abstract classes in Java are not interfaces - in particular, the entire point of interfaces is that they're the only place where Java allows an equivalent to multiple inheritance in C++. In Java, if I want to implement AbstractFoo and AbstractBar then I'm out of luck. So itowlson is right - you can't put code in interfaces in Java, and code in abstract classes does not achieve the same thing that mixins do in other languages (including C++).
Steve Jessop
But a Java abstract class is not a Java interface.
struppi
Agreed - an abstract class only addresses that issue of partial implementation. I would disagree that the point of interfaces is to allow a measure of multiple inheritance. I would said interfaces allow a complete separation of interface from implementation before I'd cite multiple inheritance. How often does one really need MI, anyway? I've used Java for a very long time without missing it. Inheritance is overrated. Interfaces and mixins are more useful.
duffymo
I pretty much never use multiple inheritance in C++ other than for interfaces and mixins. I do miss mixins in Java, for instance I think they would be pretty useful in the abstract collection hierarchy. I don't mean to say that interfaces are in any way sneaking "real" multiple inheritance in to Java by the back door - they don't. But in terms of the type hierarchy, they are a restricted form of multiple inheritance, and they couldn't work if they weren't.
Steve Jessop
Where by "mixins", I mean MI base classes with member functions but no data members, in case that isn't clear. I have occasionally written "near-mixins", which have a data member used for one particular purpose. `boost::enable_shared_from_this` is an interesting example of why you might want that in C++. It wouldn't be useful in Java, of course.
Steve Jessop
+31  A: 

This is kinda subjective, but:

if C++ programmers could,they should code and think like a Java programmer?

No. They should code and think like C++ programmers. C++ has lots of idioms and techniques which do not exist in Java (and vice versa). You should use the idioms and thought patterns appropriate to the language, not try to write Java (or Pascal, or Fortran) with C++ syntax.

(That doesn't mean don't borrow tricks from other languages, of course...!)

itowlson
+13  A: 

You're looking at this from a Java-centric perspective. Consider for example that Java doesn't support the "RAII" style, which is well-supported by C++. The languages are different, and support different styles in different ways.

Greg Hewgill
+1  A: 

This is quite a subjective question, but, if I may share my opinion, no, C/C++ programmers should not think like "Java programmers", nor should Java programmers think like "C/C++ programmers"; Each language does one thing better and other things in its on way. However, both should think like programmers and like "Object Oriented Programmers".

Object Oriented Analysis makes us see the world as a collection of objects and their methods, the classes that group them, their common interfaces, etc. Your language may vary in the way those constructs are described, but in the end, the goal is the same. Once you understand WHAT you will implement and choose the language, then you start thinking of HOW to implement it, which is the same as telling you to choose between thinking as a "Java Programmer", "C/C++ Programmer" or a "C# programmer".

Bruno Brant
+2  A: 

Probably the most important difference between C++ and Java is that Java has a garbage collector and C++ does not. This means that in C++, whenever you create an object on the heap, you need to know how you will be able to clean it up later. In Java you can always safely return an object knowing that the garbage collector will sort out its deletion.

So, if you code C++ like you code Java you will have leaks galore.

doron
+1  A: 

There are many Java features which are difficult for the C++ programmer to reproduce. Interfaces and inner classes are not among them, but in Java the compiler enforces that you can't have code in interfaces, whereas in C++ the programmer just has to write classes without any code. In Java inner classes you have the secret built-in parent.this field, whereas in a C++ nested class you have to do the typing and make that member explicit. C and C++ are both rather more DIY than Java.

So it depends what you think the feature is. If you think the Java interface feature is, "I can use polymorphic interfaces in my design", then that's trivial in C++. If you think the Java interface feature, "it is not possible to define method bodies in interfaces", then C++ doesn't have it.

If you want to precisely reproduce the features of Java, and "think like a Java programmer", then the proper thing to do is to program in Java...

Steve Jessop
I understand what you represent,but if you are in a concrete project and need to design the class hierarchy,interface.would you try to implement something like interface of java,because it would produce a better class interface.
Jichao
@jcyang: I wouldn't design a class hierarchy. Why'd I need one of those? I'd define the *concepts* that my classes had to support, and whenever possible, I'd avoid dependencies on specific classes *or* interfaces with templates. If I *did* have to design a class hierarchy, and I absolutely needed interfaces, I'd use pure abstract classes. Those are simply C++'s way to provide interfaces.
jalf
If I needed runtime polymorphism then I'd use it, and I might well use interface-style base classes with only pure virtual functions. But I don't consider this to be "thinking like a Java programmer". Java has explicit language support for the pattern, that C++ doesn't have, but the pattern is hardly special to Java. If I was faking up "finally blocks" and garbage collection, and if I wasn't using any templates at all, only interfaces with virtual calls, then I'd consider maybe I was thinking like a Java programmer, and my code perhaps would be better written in Java.
Steve Jessop
@jalf:how to avoid dependencies on specific classes or interfaces with templates?could you explain it to me.thx.
Jichao
@jcyang: `template <typename T> void Foo(T t) { t.baz(); }` <- This function doesn't depend on a specific class or interface. It doesn't have to be `IBazable` It works with *any* type T that supplies a `baz` member function. An even better, and more extensible approach might be `template <typename T> void Foo(T t) { baz(t); }`. Now T might even be an existing type that doesn't have a `baz()` method. We can define our own outside the class and "patch it up" so the type can be used even if it wasn't originally intended to be "`IBazable`". Does that make sense?
jalf
A simpler example is in the standard library. The free function `std::sort` takes two parameters of some unknown template type `T`. There are no interfaces or anything to constrain what type it must be. The only requirement is that `T` must support the concept of a bidirectional iterator. That is, it must expose the members and typedefs expected of a bidirectional iterator. If it does that, then `sort()` will work, whether or not the arguments are derived from some predefined interface.
jalf
And because of that, std::sort works with pointers. Which is nice. Similarly, you can write templates which work both with built-in integral types, and with big-number types like GMP's C++ wrappers. In Java, conversely, you can't do anything useful with a java.lang.Number, which is the only type in common between java.lang.Integer and java.math.BigInteger.
Steve Jessop
+2  A: 

C++ has a single powerful concept (classes + multiple inheritance) to achieve a set of goals. Java has two less powerful concepts (classes + single inheritance and interfaces + multiple inheritance); if you combine them, you can do some of the things that C++ can do, but not all of them (e.g. interfaces with default implementations). So saying that Java is "more sophisticated" in this respect sounds a bit weird to me.

The better question is: Is the additional power that C++ gives you a good thing or not?

nikie
why downvoted?i think its a fine statement.
Jichao
+6  A: 

I have to say "good" Java design is almost uniformly terrible. I've never seen so much code duplication, ridiculous layered levels of abstraction (but almost never the abstractions that would have actually made sense in the situation) as when looking at Java code.

There are many good features of C++ that Java has no equivalent for. Features that enable cleaner, more robust and more elegant designs.

C++ programmers should code like C++ programmers. For two very good reasons:

  • They have to respect the weaknesses and flaws of the language. Trying to pretend you're in a garbage-collected language when you're not is a recipe for disaster. And trying to implement GC-like semantics on top of a language like C++ is probably even worse.
  • And just as importantly, they should exploit every strength of the language. When you can get truly generic collection classes with zero overhead and a sophisticated iterator implementation, why on Earth would you throw it away? When you've got one single sorting function that works for any container and even more generally, for any sequence of objects of any type, why would you throw it away?

Since you mention interfaces as an example of a feature C++ programmers should emulate, there are two important counterpoints:

  • C++ has interfaces in the form of abstract classes. The semantics are slightly different, but they can be used to serve the same purpose.
  • C++ doesn't need interfaces as much, because it has templates and concepts relying on compile-time ducktyping. Rather than having every iterator derive from an IIterator interface, we can simply define how an "iterator" should behave, and write a class that supplies members with the same names. As long as it "looks like" an iterator, it can be used as an iterator. Template metaprogramming tricks even make it possible to adapt existing classes to "retrofit" them to support a concept they weren't designed for. For example, raw pointers (as taken from C) work as perfectly valid iterators, despite missing a few typedef members. And without even being classes in the first place.

Of course, C++ has plenty of weaknesses too. But it is not simply an "inferior Java". It is a different language. There is no need for C++ programmers to emulate Java features.

As I read in Thinking in java

Java books are rarely good sources of information about C++. ;)

jalf
Some of the design in Java language is silly, but templates are a complete mess. If you have an iterator at all (which makes much less sense most of the time than people seem to think) how is it better to have to generate out 999 iterators and throw out 998 of them every time you compile or be forced to recompile the whole project to make sure you didn't screw up the base class? Templates are fine to some extent but they get used far more in C++ than they would if other features worked better.
Charles Eli Cheese
@Antiguru: You'll note that I didn't mention compile times as one of C++'s strong points. But the question was not "is it a good thing that Java code can be compiled faster than C++" code. Regardless of the impact on compile times, but they allow some useful abstractions that'd be impossible to implement in Java.
jalf
*Thinking in Java* was written by Bruce Eckel (http://en.wikipedia.org/wiki/Bruce_Eckel), who I believe knows a fair bit about C++ also. :)
Michael Myers
And yet he claims that "C++ does not have interfaces", and that "a *clever* programmer may simulate them"? But yes, you're right, he knows his stuff. But he can apparently still write some silly things about C++ ;)
jalf
A: 

I can't think of anything immediately, so I'm going to answer a firm NO, and dare the internet to provide counter examples.

Based on my interpretation of the 20:33:27 edit, we're looking for something that

  • (Good) C++ programmers were not already doing
  • ... that is supported by popular implementations
  • ... and is appropriate for the problem domains where C++ is an appropriate language choice

Tough parlay, that.

Some possible places to look for counter examples: Unit Testing Synchronization

VoiceOfUnreason