Overwrite one method in c++ class - c++

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?

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();
};

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().

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?

Related

How to defined a static interface in base class and make sure the interface must be implement in derived class?

It is very easy that we can make sure derived class must implement interface defined in base class.
That is pure virtual function.
For example:
class BaseClass
{
...
virtual void print()=0;
...
}
class DerivedClass :public BaseClass
{
// function must be implement, otherwise compiler will complain ...
void print()
{
}
};
Can we defined a static interface in base class and make sure the interface must be implement in derivate class?
I want something like this
class BaseClass
{
...
static void print(); // base class only define static interface
...
}
class DerivedClass :public BaseClass
{
// derived class must implement interface, otherwise compiler will complain ...
static void print()
{
}
};
I have no idea about this.
Thanks for your time.
It is not possible to make a virtual static function. For the simple reason that when calling a static function, you always know the class that defines that function in compile time. Unlike virtual functions, where you don't know the type of the object whose method you're calling.
For example:
class A
{
public:
virtual void f() {printf("A");}
};
class B : public A
{
virtual void f() override {printf("B");}
};
void g(A& a)
{
a.f();
}
int main()
{
B b;
g(b);
return 0;
}
In the above example, inside the function g, the correct function is invoked (B::f). Even though while compiling the function it is not known what the type of its argument is (it could be A or any class derived from A).
Without making f() virtual, you would have overloaded the method f, rather than overridden it. Which means that in the following example, the output would be "A", even though you might expect it to be "B":
class A
{
public:
void f() {printf("A");}
};
class B : public A
{
void f() {printf("B");}
};
void g(A& a)
{
a.f();
}
int main()
{
B b;
g(b);
return 0;
}
This may cause serious bugs, and it is suggested to never overload base class methods, and to always use the override keyword when overriding a virtual method to escape those bugs.
When making a static function, you can simply overload it, it would not create a compilation error. However, you probably never should overload it, because it may hide a bug that is very difficult to track (you are certain that B::f() is being called while actually A::f() is being called).
Furthermore, it is not possible to 'force' the derived class to implement a static interface, because there is no such thing as a static interface. Because you have no virtual static functions, you may not pass a reference or pointer to the interface that would implement this function.

How to make the inherited function to call the derived class function without virtual functions

Let's assume I have class A and B as follows:
class A
{
public:
void function_1(){ /*other codes*/; function_2();};
void function_2();
};
class B:public A
{
public:
void function_2(); // this function is reimplementation of A::function_2()
};
Now assume in the main code I have
B objB;
objB.function_1();
From my test if I leave the code as above, it will still call A::function_2() internally when objB.function_1() is called.
I want objB.function_1() will internally call the B::function_2(), not A::function_2(). Is it possible to do it provided that I cannot change the code of A class?
Is it possible to do it provided that I cannot change the code of A class?
As others already pointed out in comments, that's not possible without making function A::function_2() a virtual function.
So if you can't change class A that's not possible.
One option is to reimplement A::function_1() in your derived class B.
Though you could provide a wrapper class for A that provides virtual functions which can be overridden in derived classes and makes that easier for future inheritors:
class AWrap {
protected:
A wrappedA;
public:
virtual void function_1() {
// Reimplement A::function_1() "other codes"
function_2();
}
virtual void function_2() {
wrappedA.function_2();
}
};
class B : public AWrap {
public:
void function_2() override {
// Implement the B specific stuff
}
};

C++: Override method which has the same name as the class

Let's say I have a nice looking base class called base:
class base
{
public:
virtual void foo() const = 0;
};
Now, I have a class named foo that I would like to inherit from base and override base::foo:
class foo : public base
{
public:
virtual void foo() const override;
};
This is illegal in C++, as you are not allowed to name a method the same thing as the class (C++ greedily believes methods with the same name as the class are constructors, which are not allowed to have return types). Is there any way around this that doesn't involve changing the name of the class or method? I want external users to be able to create foo classes without the knowledge that there is a method base::foo called by someone else (imagine foo can be both a noun and a verb).
Is there any way around this that doesn't involve changing the name of the class or method?
No, there isn't.
All methods named foo are special in class foo -- they are constructors. Hence, they cannot be overridden virtual member functions.
I'll take a wild guess and just say NO.
You can have a lot of ambiguities in C++ (that sometimes have to be explicitly disambiguated), but I don't even see a way how a compiler or programmer could disambiguate this situation. Well, A programmer can (a function with a return type is obviously not a constructor), but C++ can't.
In C++, the only method that can have the class' name is its constructor.
So, no. You can't.
Okay, here's my (slightly evil) solution...
// Create an intermediate class which actually implements the foo method:
class foo_intermediate : public base
{
public:
virtual void foo() const override;
};
// Derive from that class and forward the constructor along
class foo : public foo_intermediate
{
public:
using foo_intermediate::foo_intermediate;
private:
friend class foo_intermediate;
// Actual implementation for the foo function goes here
void foo_impl() const;
};
// In some CPP file:
void foo_intermediate::foo() const
{
// Need to access the typename foo via namespace (global here)
static_cast<const ::foo*>(this)->foo_impl();
}
Actually calling foo is a bit funny, since this can't work:
void bar()
{
foo x;
x.foo(); // <- illegal attempt to access to the foo constructor
}
You must access through an alias:
void baz()
{
foo x;
base& rx = x;
rx.foo(); // legal
}
As an alternative, you can use a typedef:
class foo_impl : public base
{
public:
virtual void foo() const override;
};
using foo = foo_impl;
This gets around the issue of calling x.foo(), since it no longer appears as a constructor access.
I made a Gist so others could play with the two solutions if they are so inclined.

Overloading implemented virtual function

Suppose I have a class Foo
class Foo{
public:
bool virtual bar(){return false;}
};
And class FooFoo inheriting Foo. bar() is not overriden in class FooFoo. I cannot change the headers of Foo or FooFoo. Is it then at all possible to override the default implementation of bar() in FooFoo?
This is impossible; you can't modify a class without modifying it, as it were.
Your best option is probably to publicly inherit from FooFoo and override in the derived class.
Is it then at all possible to override the default implementation of
bar() in FooFoo?
No, but you could derive another class, and use that class "polymorphically" via the base. This should have the same effect, given that the original client of Foo does his work through the interface of Foo, as he should
Therefore:
//In Foo.h - may not be modified
struct Foo
{
virtual bool bar(){ return true;}
};
//In FooFoo.h - may not be modified, hence no override...
struct FooFoo: public Foo
{
virtual bool bar(){/**/}
};
//FooFoo_2 - The new class - may be implemented in terms of FooFoo
struct FooFoo_2: public Foo
{
virtual bool bar() override{/*new implementation*/}
};
void fooUser( Foo& foo )
{
bool result = foo.bar();
if (result ){} //etc
}
int main()
{
FooFoo_2 theNewImplementation;
fooUser( theNewImplementation );
return 0;
}
Note also that "override" is not required, but if added, one would get a compiler error if the signature of bar changes in base (which would cause derived to not be virtual anymore) - something that one would want to be aware of.
Regards
No. You can only override a function by declaring the override within the derived class's definition.
In C++ language no. In particular implementation it is technically possible to manually modify vtable for class FooFoo and replace pointer to Foo::bar() to something else. Of course this would be an ugly hack and neither recommended practice in any sense nor guaranteed to work even when something changes (for example compilation flags).
No. You'll need to declare the override in the FooFoo class definition, which you said you cannot do. If you tried to define the overriden function in FooFoo, outside of the class, you'd run into errors, since it was not previously declared to be overriden in FooFoo.
Also note, in C++11 and later, you should use the override attribute. Example:
struct FooFoo : Foo
{
bool bar() override { return true; }
};

Return child class into base class object

I am trying to get my head around some inheritance problem in C++:
Consider a base class Foo() with a method method() and its derived class Bar. Now I override the method in Bar.
class Foo{
public:
double method();
}
class Bar public: Foo
{
public:
double method()
}
And a function like this:
Foo get_bar(){
Bar bar()
return bar
}
Calling the function get_bar() I'd like to be able to call Bar::method()
Foo foo = get_bar();
foo.method() (-> which should be Bar::method)
Is this possible? And if, how? I think I am making a fundamental mistake here which I don't see. Thanks!
To override (not overwrite) a function, it must be virtual:
class Foo {
public:
virtual void method();
virtual ~Foo() = default; // technically optional, but usually needed
};
For completeness, here is the corrected syntax for the derived class:
class Bar : public Foo {
public:
void method() override; // override is optional, but a good idea
};
Polymorphism only works on references and pointers, so your function would have to return one of those, not a base-class object. As it is (once the syntax is fixed), it slices the Bar object to return a copy of its Foo, which would not give you the overridden function that you want.
There's no existing object to return a reference to; so you'll probably have to dynamically create one an return a pointer. Unless you enjoy long debugging sessions, use smart pointers to manage dynamic objects:
std::unique_ptr<Foo> get_bar() {
return std::unique_ptr<Foo>(new Bar); // C++14: make_unique<Bar>();
}
If I understand your question correctly you want get_bar() to return a child class Bar as if it was the base class Foo such that you can subsequently call method on it and it will call Bar::method(). Yes, you can do that. It is called Polymorphism.
In order to achieve this get_bar() needs to return a pointer otherwise you will encounter the slicing problem and won't get the polymorphic behaviour you are looking for. As get_bar() is a factory function transferring ownership to the caller it is preferable to return a smart-pointer like unique_ptr or shared_ptr:
std::unique_ptr<Foo> getBar() {
return std::make_unique<Bar>();
}
Foo::method() needs to be virtual in order to override it in Bar. And in order to destroy Bar properly when the Foo pointer is deleted Foo must have a virtual destructor:
class Foo {
public:
virtual void method();
virtual ~Foo(){}
};
class Bar : public Foo {
public:
void method() override;
};