4

I'm working on translating a small package from C++ to Java. I've never really used C++, so some of the syntax is a bit of a mystery. In particular, I'm having difficulty working out what the Java equivalent to this would be:

file: SomeClass.cpp

SomeClass::SomeClass( BitStream* data, const char* const filename ) :
    data( data ), cipher( filename ), iv( new Botan::byte [cipher.BLOCK_SIZE] ),
    ivBitsSet( 0 ), keyMaterialRemaining( 0 ), keyMaterial( new Botan::byte [cipher.BLOCK_SIZE] ) {}

I'm happy with (in Java):

public SomeClass{
  public SomeClass(InputStream data, String filename){

  }
}

but I'm not sure what to do with the stuff after the : in the C++. Are they fields? Optional parameters? Apologies for trivial question, but haven't got far with Google on this...

4 Answers 4

9

Everything after ":" is called the member initialization list, in C++ this is one way of initialising the members of this class. For example from your code, "data" is a member of SomeClass, so the equivalent in Java would be a simple assignment in the body of the constructor.

this.data = data;

etc. for all the other members

Sign up to request clarification or add additional context in comments.

Comments

4

Those are field initializer lists. They set the initial values for the fields.

The Java-Version is something like

public SomeClass{
  public SomeClass(InputStream data, String filename){
    //either set the field directly...
    this.data = data;
    //...or call the constructor, depending on the type
    this.cipher = new Cipher(filename);
  }
}

Note that this are not necessarily simple field setters, they may also be calls to the field type's constructor.

Comments

2

cipher(filename) is equivalent to writing cipher = filename;

1 Comment

Not so. But cipher=filename is as close as Java can get to what cipher(filename) does.
1

This simply is the C++ way to initialize all the class members.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.