Reputation: 2742
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();
?
Upvotes: 0
Views: 151
Reputation: 1751
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
Upvotes: 0
Reputation: 129764
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; }
};
Upvotes: 0
Reputation: 500177
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
.
Upvotes: 0
Reputation: 101446
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.
Upvotes: 1