Don’t forget that virtual

I am not really a C++ programmer. I usually code in C, and I think all C++ I’ve ever written involved a couple of vectors and maybe one or two classes. So what I’m writing here is certainly old news for C++ programmers.

The other day, while I was reading this essay about the Liskov Substitution Principle, I was intrigued by a situation presented in page 4, which deals with class inheritance and method overriding.

Methods that can be overriden must be declared virtual in C++. I really didn’t know about that. I am used to Java’s behaviour, which I illustrate below:

/*
 * A.java
 */
 
public class A {
 
	public void bar() {
		System.out.println("bar");
	}
}
 
/*
 * B.java
 */
 
public class B extends A {
 
	public void bar() {
		System.out.println("Bar!");
	}
}
 
/*
 * C.java
 */
 
public class C {
 
	public void call(A o) {
		o.bar();
	}
}
 
/*
 * Main.java
 */
 
public class Main {
 
	public static void main(String [] args) {
		A a = new A();
		B b = new B();
		C c = new C();
 
		c.call(a);
		c.call(b);
	}
}

The code above will produce the following output:

bar
Bar!

If I wanted to do the same thing in C++, I would have to write it this way:

#include <iostream>
 
class A {
public:
	A() {}
	virtual ~A() {}
	virtual void bar() { std::cout << "bar" << std::endl; }
};
 
class B : public A {
public:
	B() {}
	virtual ~B() {}
	void bar() { std::cout << "Bar!" << std::endl; }
};
 
class C {
public:
	C() {};
	virtual ~C() {};
	void call(A &o) { o.bar(); }
};
 
int main(int argc, char *argv[]) {
	A a;
	B b;
	C c;
 
	c.call(a);
	c.call(b);
 
	return 0;
}

The output will be the same as the Java program, but pay attention to the virtual modifier placed before the declaration of the bar method in A. If I remove it, the output will be:

bar
bar

Even though B declares a method called bar, it is completely shadowed by the implementation inherited from A. In my opinion, Java’s behaviour is a lot more intuitive. I wonder how many people might have spend hours, maybe days, looking for a bug in a C++ program when the problem was that a method was not declared virtual and method calls weren’t occuring as expected.

I talked about this with Otávio, and he found out C# has a similar characteristic. In C#, a method must be declared as virtual for its subclasses to override it AND the subclasses must use override when overriding the method. Here’s the code he provided me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
   class Alice
   {
       public virtual void sayHello()
       {
           Console.WriteLine("Hello, world");
       }
   }
 
   class Bob : Alice
   {
       public override void sayHello()
       {
           Console.WriteLine("Hello, world!");
       }
   }
 
   class Echo
   {
       public void say(Alice toto)
       {
           toto.sayHello();
       }
   }
 
   class Program
   {
       static void Main(string[] args)
       {
           Alice a = new Alice();
           Bob b = new Bob();
           Echo e = new Echo();
 
           e.say(a);
           e.say(b);
       }
   }
}

Some people argue that this makes code clearer, but I’m not convinced. Why not make overriding implicit?

Posted in C++, English, Programming | 1 Comment

SWI-Prolog Easter Egg

swi-prolog-easteregg

Found it by accident :)

Posted in English, Nerd, Prolog | Leave a comment

New toys

Yesterday I bought myself three new toys:

f-22-raptorAn F-22 Raptor model

ka-52-alligatorA KA-52 Alligator model

rc-f1-ferrariAn RC F1 Ferrari

Posted in English, Nerd, Personal, Pictures | Leave a comment

This week’s links

I’m gonna start posting links to news, articles or blog posts which I find interesting on a weekly basis. I expect to do this every Friday or Saturday from now on. Here’s the first batch:

  • 13 things that do not make sense: 13 things that still puzzle the minds of scientists around the world.
  • It’s not magic!: Microsoft’s Eric Lippert on “magic code” (code that people don’t realize someone actually had to implement)
  • Orthogonality: a long but interesting post about programming language orthogonality

Not much for this week I guess, but I hope to collect more links in the next weeks :)

Posted in English, Links | Leave a comment

QuickSynergy 0.9.0 released

Yesterday I released version 0.9.0 of QuickSynergy for Linux. Here are some screenshots:

QuickSynergy 0.9.0 Screenshot

Share mode

QuickSynergy 0.9.0 Use mode

Use mode

QuickSynergy 0.9.0 Settings

Settings

QuickSynergy is a graphical user interface for Synergy developed by me and Otávio Cordeiro, which aims to ease the task of setting up Synergy on Linux and Mac OS X systems, for which there are no official GUIs. Synergy is an application that allows you to share a single mouse and keyboard between two or more computers across a TCP/IP network. It is much like a “software KVM switch“, but without the V in KVM.

Release notes for version 0.9.0:

  • Allow setting client name in Use mode.
  • Configurable path to synergy binaries.
  • New configuration file format (key-value).
  • New Share mode image in main window.
  • Minimum required GTK version now 2.10.
  • Bug fixes.
Posted in English, Linux, Projects | Leave a comment

Fractals in Logo

Today I was reading a blog post about Logo and I decided to play a little with UCBLogo (Berkeley Logo) and try to draw some fractal (more specifically, L-Systems) with it.

Here is a Koch Curve:

Koch Curve

The code:

to M n
  ifelse notequal? :n 0 [
    M :n - 1
    lt 90
    M :n - 1
    rt 90
    M :n - 1
    rt 90
    M :n - 1
    lt 90
    M :n - 1
  ] [
    fd 10
  ]
end

cs
pu
lt 90
fd 150
rt 180
pd
M 3

And here is a Fractal Plant:

Fractal Plant

The code:

make "stackpos []
make "stackhead []

to store
  push "stackpos pos
  push "stackhead heading
end

to restore
  pu
  setpos pop "stackpos
  setheading pop "stackhead
  pd
end

to F n l
  ifelse notequal? :n 0 [
    F :n - 1 :l
    F :n - 1 :l
  ] [
    fd :l
  ]
end

to X n l
  if notequal? :n 0 [
    F :n :l
    lt 25
    store
    store
    X :n - 1 :l
    restore
    rt 25
    X :n - 1 :l
    restore
    rt 25
    F :n :l
    store
    rt 25
    F :n :l
    X :n - 1 :l
    restore
    lt 25
    X :n - 1 :l
  ]
end

setbackground 2
setpencolor 0

cs
pu
bk 50
lt 90
fd 150
rt 90
pd
rt 45
X 5 2

The code could be a lot better, but that’s what I was able to grasp in about 3 hours. The last time I had really used logo was in primary school, when I was 8 or 9-years old.

I don’t know if it’s a problem with my Fractal Plant function code or if it’s a bug in UCBLogo, but sometimes execution froze completely and I had to hit Alt+S to stop it and call the function again until it worked. I also don’t know if that’s a limitation of UCBLogo or if I just haven’t studied it enough, but I couldn’t find out a way to unset a variable or redefine a function.

Anyways, Logo is absolutely fun to play with. As the author of the previously mentioned post said, it is kind of addicting to think of a set of steps and order the turtle to repeat them a few hundreds of times to see what happens. I consider the language itself a bit confusing at first, but I guess I should read more about it before forming any strong opinions on it.

Posted in Uncategorized | Leave a comment

How to install ViewVC on a Dreamhost hosted repository

I have set up an SVN repository for QuickSynergy at my recently-acquired Dreamhost hosting. Their control panel is great and setting everything up was very easy.

However, it doesn’t install any repository browsing tool such as ViewVC, and I really enjoy using that kind of thing. So I went after it and managed to install it successfully at http://svn.cesarbs.org/viewvc.cgi. The installation steps are quite simple and are listed below. I am assuming you have set a up a separate subdomain exclusively for your SVN repositories, such as svn.yourdomain.org.

  1. Download the latest ViewVC package from the official website.
  2. Extract the package somewhere in your home directory at Dreamhost.
  3. Enter the viewvc-version directory and run the viewvc-install script.
  4. Install ViewVC somewhere in your home directory.
  5. Edit the /path/to/viewvc/viewvc.conf configuration file.
  6. Point svn_roots to the path to your SVN repository (look for the svn directory in your home directory).
  7. Set default_root to svn.
  8. Copy ViewVC’s scripts from /path/to/viewvc/bin to /home/user/svn.yourdomain.org.
  9. Create a file named .htaccess under the /home/user/svn.yourdomain.org directory with the following contents:
Options +ExecCGI
AddHandler cgi-script .cgi

You are done installing ViewVC. Just access it at svn.yourdomain.org/viewvc.cgi!

Note: If you don’t want everyone to be able to see you files, you will have to configure authenticated access to your subdomain using the Dreamhost panel tool for that purpose.

Posted in English, Programming, Tutorials | Leave a comment

Rexona for Physicists

Rexona Quantum

Posted in English, Nerd, Pictures | 1 Comment

Debian Lenny no Eee

Já faz algum tempo que eu estava cansado do Ubuntu Eee (que vai passar a se chamar Easy Peasy). O controle de volume simplesmente parou de funcionar, eu não conseguia configurar o governor do cpufreq de forma permanente de maneira alguma (não adiantou colocar o comando no /etc/rc.local nem alterar os parâmetros no laptop.conf) e a interface Remix, ainda que bastante interessante, ainda tem muitas coisas que precisam ser aperfeiçoadas.

Por isso, estava decidido a instalar outra distribuição no meu Eee 701. Na dúvida entre o Arch Linux e o Debian, preferi ficar com o Debian, pois já tenho mais familiaridade com a distribuição. Achei muito bom o fato de existir uma imagem pronta para uso em EeePC’s, juntamente com um guia de instalação. A instalação foi um pouco demorada, mas fiquei contente por ver tudo funcionando de primeira, sem a necessidade de nenhuma configuração manual.

debian-eee

Ainda não tive a oportunidade de testar o WiFi, mas a interface parece ter sido detectada corretamente. A única coisa que vou ter que configurar são as teclas de função para controle do volume, o que não deve ser muito complicado. Estou bastante satisfeito até agora.

Posted in Linux, Português | 1 Comment

Am I fat?

Five kilograms. :-)

Am I fat?

Five Kilograms

Posted in English, Pictures | 1 Comment