C ++ and Java: using a virtual base class

I have some doubts when comparing multiple C ++ and Java inheritance.

  • Even Java uses multiple layered inheritance through interfaces - but why doesn't it use anything like a virtual base class, like in C ++? This is due to the fact that the java-interface members are provided with one copy in memory (they are public static final), and the methods are only declared and not defined?

  • Besides saving memory, is there any other use of virtual classes in C ++? Are there any reservations if I forget to use this function in my multiple inheritance programs?

  • It's a little philosophical - but why didn't the C ++ developers make each base class virtual by default? What is the need for flexibility?

Examples will be appreciated. Thank!

+5
source share
4 answers

1) Java interfaces have no attributes. One of the reasons for virtual base classes in C ++ is to prevent duplication of attributes and all the associated difficulties.

2) At least a slight performance limitation for using virtual base classes in C ++. In addition, constructors become so complex that it is recommended that virtual base classes have no constructors without arguments.

3) - ++ philosphy: , .

+3
  • - Java-, . , - , Java , , , .

  • - , , . , : , , . : , - / , , , Base *.

  • ++ , , , , . , , , - , . , , - , , .

+3

1. ++. , java- ++ ++.

++ ( ) static_cast < > , rtti (dynamic_cast) ( " ", , , )

2. "" , frome dred

3. , , ... ++ - ( ) - . , , , ( rioght) . , ++ ( ) ( ) - .

+2

, ++- Java. ++ . , ... Java... ... .

, , , Java. , , , ++.

http://www.jquantlib.org/index.php/Using_TypeTokens_to_retrieve_generic_parameters

, , : Java, , , , .

, . , , .

Ok. .

Java : 1. ( ) 2. javac , , ; 3. , №2, .

, Scala, №2, , , , .

"" Java ( Scala), - :

, - ++:

template<Base>
public class Extended : Base { ... }

Java :

public interface Virtual<T> { ... }

public class Extended<B> implements Virtual<B> { ... }

OK. , Extended, ?

Extended extended = new Extended<Base>() { /* required anonymous block here */ }

.. Extended. . .

OK. Extended, Virtual.

Note that during compilation, javac can check types for you, for example, in the following example:

public interface Virtual<Base> {
    public List<Base> getList();
}

public class Extended<Base> implements Virtual<Base> {
    @Override
    public List<Base> getList() {
        // TODO Auto-generated method stub
        return null;
    }
}

Well ... despite all the efforts to implement it, in the end we do poorly that an excellent compiler, such as scalac, is much better than us, in particular, it does its job at compile time.

I hope this helps ... if you haven’t embarrassed you yet!

+1
source

All Articles