1

If I have this class:

class FooBar {
    public:
        FooBar(int qux);
        void bar();

        void foo1();
        void foo2();
        //...
        void foo99();
}

How can I overwrite the bar method in FooBar, while still being able to use all the other foo method without defining them again?

Edit:

I want to use like this:

FooBar2 baz(1); // call the constructor of FooBar, FooBar(1)
baz.foo1(); //call method foo1 of original FooBar
baz.bar(); // call method bar of FooBar2

I prefer not to edit the header or implementation of FooBar.

Is it also possible to make the constructor function call the original constructor function from FooBar?

Tyilo
  • 28,998
  • 40
  • 113
  • 198

3 Answers3

2

You make bar virtual, because overriding only applies to virtual methods.

Then you extend FooBar and provide a new implementation just for bar.

class FooBar {
    public:
        virtual void bar();

        void foo1();
        void foo2();
        //...
        void foo99();
};

class FooBarDerived : FooBar
{
    public:
        void bar();
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

Inheritance.

class FooBar
{
public:
    virtual void bar() { ... default implementation ... }
    void foo1();
    void foo99();
}


class FooBarVariation : public FooBar
{
public:
    virtual void bar() { ... different implementation ... }
}

FooBarVariation will act like a FooBar, but with a different implementation of bar().

tenfour
  • 36,141
  • 15
  • 83
  • 142
1

What you need is Function Hiding and not overridding.
Overidding applies only when the virtual keyword is involved.

Just redefine the method you want to overload in your derived class and you should be fine.

class YourClass: public FooBar 
{
    public:
       void bar(){}
};

The class YourClass objects can access all the methods of FooBar because those are public methods and your class derives publically from it, while YourClass::bar() hides FooBar::bar().

EDIT:
Your edited question makes it clear that Function Hiding is indeed what you need.
Here is a online demo of function hiding achieving what your requirement is.

Is it also possible to make the constructor function call the original constructor function from FooBar?

You can use the Member Initialization list to call appropriate Base class constructor through derived class constructor.

Good Read:
What is this weird colon-member (" : ") syntax in the constructor?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • @tenfour: *"How can I overwrite the bar method in `FooBar`, while still being able to use all the other `foo` methods without defining them again?"* seems pretty clear/intuitive to me. – Alok Save Aug 24 '12 at 10:24
  • 2
    It's not clear if he wants hiding or overriding; is he trying to usurp the behavior of code that uses `FooBar` objects? Or does he just want to create new objects that conveniently inherit stuff that `FooBar` does? – tenfour Aug 24 '12 at 10:27