0

Firstly, let me apologise for the title, I honestly couldn't think how to word it better. The example below should make my question a little clearer:

class Foo    {
    public:
      Foo(int x);
    };

class Bar : public Foo
{
public:
  Bar(int y) : Foo(y);
};

Demonstrates code that would force the Bar constructor to call the Foo constructor with parameter Y. My question is, is there a similar method for inheriting a derived class function to call a base class function?

For example all calls to Bar.Func(); would also automatically call Foo.Func();?

1

4 Answers 4

1
class Foo    {
    public:
      Foo(int x);
  void DoIt();
    };

class Bar : public Foo
{
public:
  Bar(int y) : Foo(y);
  void DoIt();
};

void Bar::DoIt()
{
  Foo::DoIt();
}

If Foo is intended to be derived from and used polymorphicly, you should declare DoIt as virtual. In addition, you will also want a virtual base class destructor.

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

2 Comments

I apologise I wasn't exactly clear on this, I'm currently solving my problem exactly as you suggested with a manual call in Bar::DoIt to Foo::DoIt. As with the constructor example in my question, is there a way to do this in the class interface similar to the constructor Bar(int y) : Foo(y) Say for example void DoIt() : Foo::DoIt() ?
If I understand you correctly, then no. There is no initializer list for functions. You must call the function explicitly in the body of the function.
0

Automatically, no. You can use Base::member() to call it, though.

struct foo {
    void frob() { std::cout << "foo::frob" << std::endl; }
};

struct bar : foo {
    void frob() { foo::frob(); std::cout << "bar::frob" << std::endl; }
};

Comments

0

Any public function declared in Foo is also accessible via Bar (the same function will get called). If you may need to override the function in Bar to alter its behaviour, make it virtual.

Comments

0

This is the code you'll need if you want to 'inherit' the function statements for a function F() from its base. Declare F() virtual in Foo, implement some statements there. Then declare F() in Bar and make a call to Foo::F() at the beginning of the implementation of Bar::F():

class Foo {
public:
  Foo(int i) { cout << "Foo(" << i << ") called." << endl; }
  virtual void F() { cout << "foo::F() called." << endl; }

  virtual ~Foo() {};
};

class Bar : public Foo {
public:
  Bar(int i) : Foo(i) { cout << "Bar(" << i << ") called" << endl; }
  void F()  { Foo::F(); cout << "bar::F() called" << endl; }
};

int main(int argc, char** argv) {
  Bar b(3);
  b.F();
}

gives

Foo(3) called.
Bar(3) called
foo::F() called.
bar::F() called

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.