In C++ what is the command corresponding to Java super()?

Asked

Viewed 658 times

4

In Java:

public class Teste extends Testando
{
    private String nome;
    private int numero;
    public Teste(String teste, String nome, int numero)
    {
        super(teste);
        this.nome = nome;
        this.numero = numero;
    }
}

What is the command corresponding to super() in C++?

2 answers

8


You call explicitly by the class name, because in C++ there is multiple inheritance and can have more than one ancestor. Roughly it would be this:

class Teste : public Testando {
    String nome;
    int numero;
    public:
        Teste(String teste, String nome, int numero) : Testando(teste) {      
            this.nome = nome;
            this.numero = numero;
        }
}

I put in the Github for future reference.

  • 1

    I was writing a reply that was the second example, but since you did +1

  • I think the second seems to me more "organized" and even more common, I do not know how is the standard in C++11 and 14, if there is any pattern, I personally divide the . hpp and the . cpp and make the "super" call on the . cpp, but of course this is how I do, to which I researched a little (unfortunately old links) did not find any definitive pattern, so both examples seem good (although I prefer the second).

  • I think at first it can also be without the name of the class, for example: ::Testando(teste). Not?

  • 1

    @Guilhermenascimento I prefer the second, I put the first to look like what he did. I remember something that becomes problematic when you do the first one, but I don’t remember what. I used little C++, never studied thoroughly. I arranged as Luizvieira said.

  • I have the impression that the first example is wrong: it is calling the base class constructor and creating a temporary one, which is discarded...probably the compiler should warn. The second mode is the correct way to call the constructor of a base class.

2

There is no direct relationship in C++.

It is possible to do something similar if you create a super typedef for all classes that want to use this feature, as in the case below:

class Derivada: public Base
{
   private:
      typedef Base super; // não deve ser público porque cada classe pode 
                          // ter apenas uma classe super
} ;

And then you could use super in place of the name of the base class, as in the example:

super::meumetodo();

However, it is not recommended to abuse this resource. In C++ there is the possibility of multiple inheritance and this would complicate the solution, and may cause confusion.

  • 1

    And if you have multiple inheritance?

  • It won’t work, of course. That’s why I commented that it would create confusion... even if you choose one of the classes to be the super and the other consider interface...

  • That’s right, in the rush I didn’t even see :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.