the Flagship of independent news, reviews and resources for Developers and Users of Samsung's mobile platform Bada
Bada Tutorials, Fundamentals

Bada/C++ Tips for Java developers

Before I started programming in Bada I haven’t touched C++ in a decade. My programming languages of choice for desktop/mobile programming are C# and Java just because they are so much easier to program. Sure, a low-level programming language is awesome from the control and performance point of view. However, it can become a nightmare to developers that have never worked in a similar environment. This post will be an on-going update of pitfalls I have found from the Java developer’s point of view.

Creating a new Class Object

Although Java syntax is very similar to C++. There are different small things that do not work the same way. Consider the following java code:

MyClass myVar = new MyClass();

The keyword new initializes and returns a new object in Java (the “MyClass myVar” is just a declaration of the variable and can be somehow compared to a pointer in C++). However, in C++ “new” returns a pointer to the created object:

MyClass* myVar = new MyClass();

In order to declare AND initialize an object in C++ you just do:

MyClass myVar;

Memory leaks and scope

When creating an object with “new” in C++ you are reserving a memory in heap which has to be deleted when you have finished working with it. Otherwise you are risking memory leaks. In Java the object exists as long as there is a reference to it. As soon as it’s not used any more the Java garbage collector deletes it automatically. In C++ you have to do it explicitly using a pointer to that object:

MyClass* myVar = new MyClass(); //we create a myVar pointer and point it to the myVar object created in heap memory.
delete myVar; //we explicitly free the memory reserved in heap

All variables in C++ declared using “TypeName variable_name” are automatically destroyed as soon as the scope they were declared in has finished (since they are declared in stack memory, which is emptied as soon as the scope has ended). Consider the following example in C++:

int foo(){
	int a = 10;
	return &a; // !!! "a" will be destoryed as soon as this function ends!
}
void main(){
	int* b = foo(); // the memory address returned by foo() is not reserved any more and might contain another/incorrect data!
	cout << *b;
}

The example above poses a serious bug which might be very hard to track down. The function foo declares variable “a” and returns an address to a, which is later on assigned to pointer b in main(). The problem is that a is automatically destroyed after foo() has finished. This might work sporadically, while the momory that was reserved by a is not claimed, which will make debugging even harder. The correct code should look like this:

int foo(){
	int* a = new int(10); // a is a pointer to an object declared in heap
	return a;
}
void main(){
	int* b = foo(); // the memory address returned by foo() is still valid since it is preserved in heap after function foo() has ended.
	cout << *b;
	delete b; // IMPORTANT!
}

Here, we declare the variable in heap memory using “new”, which is preserved when foo() has finished, and pass the pointer back to main(). After you are finished with “b”, you have to delete it from heap to avoid memory leak!

String quotation marks!

Wow. This one took me several hours to debug. Thanks to wit, who spotted the problem in my code! While not being directly related to Java, in many programming/scripting languages you can use single or double quotes indifferently to declare a string. Make sure to use DOUBLE QUOTES for Strings in C++. The following code compiles and works ok til an unexpected crash in simulator, with absolutely no feedback from the debugger:

//call a function foo(String bar) that accepts String as a parameter:
foo('My String'); //compiles OK, but is silent and deadly during runtime!

Maze of const function params

In C++ it is possible to declare function parameters as “const”. This is called “const correctness” and serves to ensure the caller that the passed parameter (by reference or as a pointer) won’t be modified. Bada API functions use a lot of const parameters. Take the most simple Bada Form Project with a Form and just one button on it. Let’s say you want to disable the button once it is clicked. The Form1.cpp has an Event that is called when the button is pressed and this is where we want to disable the button. However, the following code will not compile (since source is const!):

void
Form1::OnActionPerformed(const Osp::Ui::Control& source, int actionId)
{
	switch(actionId)
	{
	case ID_BUTTON_OK:
		{
			source.SetEnabled(false);
		}
		break;
	default:
		break;
	}
}

By the book, you should create a local copy of the const params to work on. But creating a local copy of the source is pretty much useless in the example above. I have found a workaround would be to create a local pointer to a de-const-ed cast of the param. Or cast it directly. This is probably bad coding, and wit will most likely break my neck for it. But it works! :D Here’s the code:

Osp::Ui::Control* mySource = &(Osp::Ui::Control)source;
mySource->SetEnabled(false);
//OR:
((Osp::Ui::Control)source).SetEnabled(false);

More coming soon!

There were several other issues I have noticed, but failed to write them down. :-D I’ll post them next time. And if you have any more, let me know! Meanwhile, make sure to read this page on wiki: Comparison of Java and C++!

Sparky

Related posts:

  1. 10 Tips To Boost Your App Sales
  2. How to win the bada developers challenge?
  3. Bada Developers Challenge: Prizes and Categories
  1. 4 Responses to “Bada/C++ Tips for Java developers”

  2. By Angel on Mar 8, 2010 | Reply

    I advise you to use Deleaker ( http://deleaker.com/ ) – tool for finding memory leaks.

  3. By remy_david on Mar 8, 2010 | Reply

    You should not use that to get rid of const parameters. Instead use the C++ const_cast function:

    http://www.oit.uci.edu/dcslib/sun/compilers/c-plusplus/c%2B%2B_ug/Cast.new.doc.html

  4. By remy_david on Mar 8, 2010 | Reply

    To be more precise I think you get your example working only because you were lucky ;)

    “With casting, you can force the compiler to let you put the address of a const int variable into a normal int*. const int* and int* are, in fact, separate types. So you can cast from a const int* to a normal int* and use the pointer to try and modify data. The result, however, is undefined. The compiler is free to store constants wherever it wants (including non-writeable memory), and if you trick the compiler into letting you try to modify the constant, the result is undefined. This means that it might work, it might do nothing, or it might crash your program.”

    More:
    http://www.oit.uci.edu/dcslib/sun/compilers/c-plusplus/c%2B%2B_ug/Cast.new.doc.html

  5. By sparky on Mar 10, 2010 | Reply

    Angel: Thanks for the info! It looks like a nice piece of software and I am definitely checking it out!

    Remy_david: I knew I was mission out something! Thank you for the tip. const_cast looks like a good idea. I will look into it since const casting is not one of my strengths, yet :)

Post a Comment

Editor's picks

Copyright 2009-2010 BadaDev.com (unless otherwise stated). All rights reserved! Powered by Wordpress!