views:

1370

answers:

3

Say I have class Foo and Bar set up like this:

class Foo
{
public:
    int x;

    virtual void printStuff()
    {
        std::cout << x << std::endl;
    }
};

class Bar : public Foo
{
public:
    int y;

    void printStuff()
    {
        // I would like to call Foo.printStuff() here...
        std::cout << y << std::endl;
    }
};

As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the super.funcname() syntax. Is this possible in C++?

+9  A: 

Yes,

class Bar : public Foo
{
    ...

    void printStuff()
    {
        Foo::printStuff();
    }
};

It is the same as super in Java, except it allows calling implementations from different bases when you have multiple inheritance.

class Foo {
public:
    virtual void foo() {
        ...
    }
};

class Baz {
public:
    virtual void foo() {
        ...
    }
};

class Bar : public Foo, public Baz {
public:
    virtual void foo() {
        // Choose one, or even call both if you need to.
        Foo::foo();
        Baz::foo();
    }
};
Alex B
+13  A: 

The C++ syntax is like this:

class Bar : public Foo {
  // ...

  void printStuff() {
    Foo::printStuff(); // calls base class' function
  }
};
sth
+2  A: 

Just in case you do this for a lot of functions in your class:

class Foo {
public:
  virtual void f1() {
    // ...
  }
  virtual void f2() {
    // ...
  }
  //...
};

class Bar : public Foo {
private:
  typedef Foo super;
public:
  void f1() {
    super::f1();
  }
};

This might save a bit of writing if you want to rename Foo.

MartinStettner